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
  • 178,213
  • 47
  • 333
  • 501
JonatasTeixeira
  • 1,474
  • 1
  • 18
  • 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
  • 526
  • 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,523
  • 1
  • 33
  • 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
  • 49,466
  • 12
  • 107
  • 135