Zaar Hai
Zaar Hai

Reputation: 9899

How to import package modules from package's __init__.py?

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?

Upvotes: 3

Views: 3933

Answers (2)

Kirill Spitsyn
Kirill Spitsyn

Reputation: 226

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.

Upvotes: 5

Claudiordgz
Claudiordgz

Reputation: 3049

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__

Upvotes: 1

Related Questions