Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use __init__.py?

Tags:

python

module

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

like image 879
Colton Phillips Avatar asked Sep 12 '11 18:09

Colton Phillips


People also ask

What does __ init __ py mean?

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.

Should __ init __ py be empty?

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.


2 Answers

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
...
like image 122
cenanozen Avatar answered Oct 27 '22 18:10

cenanozen


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
like image 24
rocksportrocker Avatar answered Oct 27 '22 19:10

rocksportrocker