Let me explain..
I want to do this:
a = "somedir.somefile"
b = "someclass"
from a import b
Well, I want to do this to import automatic all classes inside a directory, and I don't know how many classes are there.
Let me explain..
I want to do this:
a = "somedir.somefile"
b = "someclass"
from a import b
Well, I want to do this to import automatic all classes inside a directory, and I don't know how many classes are there.
a = "somedir.somefile"
b = "someclass"
module = __import__(a, globals(), locals(), [b], -1)
clazz = getattr(module, b)
now you can do this:
instance = clazz()
instance.method()
You need the __import__
built-in function. It's a bit fiddly to use, though, because it returns the top-level module, rather than the leaf of the path. Something like this should work:
from operator import attrgetter
module_path = 'a.b.c'
class_name = 'd'
module = __import__(module_path)
attribute_path = module_path.split('.') + [class_name]
# drop the top-level name
attribute_path = attribute_path[1:]
klass = attrgetter('.'.join(attribute_path))(module)
I think what you actually want to do is use __init__.py
and __all__
. Take a look at the modules tutorial for details.
Alternatively, there's exec
. It will do what you're asking, but is probably not the best way to get there.