I have the following project structure:
python/
..core/
..envs/
..default/
....__init__
....default.py
..dev1/
....__init__
....dev1.py
dynamic_inventory.py
in dev1 i have the following:
from ..default.default import BaseInventory
in dynamic_inventory:
import inspect
from envs.dev1 import dev1
print inspect.getmembers(dev1, inspect.isclass)
it gives me right code:
> [('BaseInventory', <class 'envs.default.default.BaseInventory'>),
> ('BatchProcessor', <class 'envs.dev1.dev1.BatchProcessor'>), ...
but dynamically:
import inspect
sys.path.append("python/envs")
m = __import__("dev1")
print inspect.getmembers(m, inspect.isclass)
gives me: []
how to do import module dynamically?
Thanks!
1 Answer 1
There are two issues with your code.
Firstly, when you write from envs.dev1 import dev1 you are importing dev1 from the envs.dev1 package. But with __import__("dev1"), you are importing it as a standalone module.
Secondly: with sys.path.append("python/envs"); __import__("dev1") you are importing python/envs/dev1/__init__.py, because the python/envs directory contains the dev1 directory. But you want the python/envs/dev1/dev1.py file. That's why you are getting an empty list: your __init__.py does not define any class.
Putting everything together:
import inspect
# no sys.path manipulation
dev1 = __import__('envs.dev1.dev1', fromlist=['dev1'])
print inspect.getmembers(dev1, inspect.isclass)