I have a list of module name what I want to import from __init__.py.
$ mkdir /tmp/pkg
$ touch /tmp/__init__.py /tmp/pkg/{a.py,b.py}
$ cat /tmp/pkg/__init__.py
to_import = ["a", "b"]
import importlib
for toi in to_import:
importlib.import_module(toi)
$ cd /
$ python
>>> import tmp.pkg
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "tmp/pkg/__init__.py", line 5, in <module>
importlib.import_module(toi)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named a
>>>
python 2.7.4 Ubuntu 64-bit
Question: So how do I import package modules from package's __init__.py?
asked Jul 29, 2013 at 16:26
Zaar Hai
9,9879 gold badges40 silver badges51 bronze badges
2 Answers 2
You can use relative imports for this. Try to change /tmp/pkg/__init__.py to the following:
to_import = [".a", ".b"]
import importlib
for toi in to_import:
importlib.import_module(toi, __name__)
Notice dots before module names and second argument to import_module function.
answered Jul 29, 2013 at 17:31
Kirill Spitsyn
2262 silver badges6 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
tdelaney
...or just use a simple import statement as the language intends. This is a super complicated to do something easy.
Kirill Spitsyn
..but topic starter specifically asked about importing all modules from a list. Also, with
import statement you nevertheless need to use relative imports in this scenario, like from . import a, b.tdelaney
import a,b is a list and its the normal way to import from a __init__.py file. You don't need "from ." or "." anything. "." is used for relative imports among package modules, but not __init__.py itself.Kirill Spitsyn
Indeed,
import a, b works there. Few minor points: I believe that there are no difference between relative imports from __init__.py and from other package modules; in python 2.7 you can use for that both syntaxes: with or without a dot (unless there is from __future__ import absolute_import statement); and relative imports without a dot were deprecated in python 3.Zaar Hai
Simple and elegant. Thanks Kirill! I new I was close :)
|
You must add the init at the end
import tmp.pkg.__init__
The imports should be in the same path as the init.py file otherwise they will not work
FullPath/pkg/__init__.py
init.py file
to_import = ["__HistogramObjects__"]
import importlib
for toi in to_import:
importlib.import_module(toi)
Then in your file that you want to import from
import FullPath.pkg.__init__ as im
for i in im.to_import:
print i
Your output should be:
__HistogramObjects__
answered Jul 29, 2013 at 17:11
Claudiordgz
3,0891 gold badge26 silver badges52 bronze badges
Comments
lang-py
import a, b?