I'm trying to learn how the __init__.py
file works for packaging and calling modules from different directories.
I have a directory structure like this:
init_test\
__init__.py
a\
aaa.py
b\
bbb.py
in aaa.py
there is a function called test
bbb.py
looks like this:
import init_test.a.aaa
if __name__ == "__main__":
init_test.a.aaa.test()
but this gives me ImportError: No module named a.aaa
What am I doing wrong? I've tried doing the same basic thing from a module above the package structure as opposed to inside the package and that did not work either? My __init__.py
The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.
Leaving an __init__.py file empty is considered normal and even a good practice, if the package's modules and sub-packages do not need to share any code.
You also need to have __init__.py in a and b directories
For your example to work first you should add your base directory to the path:
import sys
sys.path.append('../..')
import init_test.a.aaa
...
You have to add an empty __init__.py
into a. Then a is recognized as a sub package of init_test and can be imported. See http://docs.python.org/tutorial/modules.html#packages
Then change import init_test.a.aaa
to import ..a.aaa
and it should work. This is -- as Achim says -- a relative import, see http://docs.python.org/whatsnew/2.5.html#pep-328
If you really want to run bbb.py
, you have to put init_test/ on your python path, e.g.
import sys
import os
dirname = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(dirname, "../.."))
import sys
sys.path.insert(0, ".")
import init_test.a.aaa
if __name__ == "__main__":
inittest.a.aaa.test()
And then you can start
python init_test/b/bbb.y
or if you are inside b/
python bbb.py
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With