How do you use __init__.py?

I am trying to find out 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 it gives me ImportError: No module named a.aaa

What am I doing wrong? I tried to do the same basic thing from the module on the package structure, and not inside the package, and that also did not work? My __init__.py

+6
source share
3 answers

You must add an empty __init__.py to a. Then a is recognized as an optional init_test package 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, as Achim says, relative imports, see http://docs.python.org/whatsnew/2.5.html#pep-328

If you really want to run bbb.py , you should put init_test / in your python path, for example.

 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 
+2
source

You also need to have __init__.py in the directories a and b

For your example to work first, you must add your base directory to the path:

 import sys sys.path.append('../..') import init_test.a.aaa ... 
+7
source

__init__.py should be in the all folders that you want to use as modules. In your case, this means init_test/a and init_test/b too.

0
source

Source: https://habr.com/ru/post/897177/


All Articles