This is probably really simple, but I don’t understand it. The following works:
foo.py
class Foo:
pass
bar.py
module = __import__('foo')
foo = module.__dict__['Foo']
Afterwards, foo is the class foo.Foo as expected.
Yet, if I put a.py into a package, it stops working:
qux/__init__.py
(empty file)
qux/foo.py
class Foo:
pass
bar.py
module = __import__('qux.foo')
foo = module.__dict__['Foo']
Running python bar.py gives me KeyError: 'Foo', but the module import is still successful.
What’s going on, and how do I get it to work?
If you want to import a submodule, you can do something like this:
Note that with a
fromlistthe__import__returns the most nested name in the first parameter, so you could substitutebaz.bar.quxin the__import__call to access thebaz.bar.qux.foomodule.