Let’s say A is a package directory, B is a module within the directory, and X is a function or variable written in B. How can I import X using the __import__() syntax? Using scipy as an example:
What I want:
from scipy.constants.constants import yotta
What doesn’t work:
>>> __import__("yotta", fromlist="scipy.constants.constants")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named yotta
>>> __import__("yotta", fromlist=["scipy.constants.constants"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named yotta
>>> __import__("yotta", fromlist=["scipy","constants","constants"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named yotta
>>> __import__("scipy.constants.constants.yotta", fromlist=["scipy.constants.constats"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named yotta
Any suggestions would be much appreciated.
The python import statement performs two tasks: loading the module and makeing it available in the namespace.
will provide the name
fooin the namespace, notbaz, so__import__will give youfooOn the other hand
does not make a module available, but what the import statement needs to perform the assignmaents is baz. this corresponds to
without making the temporary visible, of course.
the
__import__function does not enforce the presence ofaandb, so when you wantbazyou can just give anything in the fromlist argument to put__import__in the “from input” mode.So the solution is the following. Assuming ‘yotta’ is given as a string variable, I have used
getattrfor attribute access.