3

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!

asked Feb 28, 2016 at 11:53

1 Answer 1

4

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)
answered Feb 28, 2016 at 12:29
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.