0

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.

Robert Harvey
  • 173,679
  • 45
  • 326
  • 490
JonatasTeixeira
  • 1,388
  • 1
  • 17
  • 24

3 Answers3

2
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()
lctr30
  • 516
  • 1
  • 4
  • 17
2

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)
babbageclunk
  • 8,205
  • 31
  • 37
0

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.

nmichaels
  • 47,648
  • 12
  • 99
  • 131