Python - Undefined class name after dynamic import -


i'm using python weeks , i'm confronted issue dynamic import. have file test.py in class defined. use class after dynamic import of test.py file.

my final goal more complex simplified still same problem.

file : test.py

class test :     def __init__ ( self ) :         print ( "instance" ) 

file : main.py

def allimports ( ) :     __import__ ( "test" ) 

what :

>>> import main >>> main.allimports() >>> myinstance = test () traceback (most recent call last):    file "<stdin>", line 1, in <module> nameerror: name 'test' not defined 

i cannot specify in fromlist element test.py have import because i'm not supposed know them.

what should ?

for solution closer intent:

import importlib def allimports(globals):     mod = importlib.import_module('test', globals['__name__'])      try:         keys = mod.__all__     except attributeerror:         keys = dir(mod)      key in keys:         if not key.startswith('_'):             globals[key] = getattr(mod, key)  # …  allimports(globals()) test # should work, can dir(test) find class. 

if module doesn't have __all__ code above /will/ clobber namespace fierce. either make sure define __all__, or modify allimports() import things want. (e.g. classes, or classes defined in module. part depends on use case.)


Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c# - Copy ObservableCollection to another ObservableCollection -

All overlapping substrings matching a java regex -