__init__.py in Python module

Python provides modules for complicate application. This modules can locate in any directory or even sub-directories. Project structure can create  like this:


For each module,  __init__.py is critical for python path search. Also, this file can do initialization jobs before module starts or just leave it in blank if no jobs to do.

Python has its path search strategy, it loads any arbitrary module in anywhere by using the keyword at the file head:

 from modulename import something

where  something can also be a class name, a function name, a constant name that defined in module1.  If importing module under a sub-directory, say this module path is “lib/sub1/sub2/mymodule.py” ,  the importing statement should be like this :

from lib.sub1.sub2.mymodule import something

python will search :

1, first search in build-in module to find target;

2, search for PYTHONPATH environment variable in system if it is set;

3, search for current project folder, load all the module name into path list;

If there isn’t __init__.py in module, python will ignore this folder and not load module into it’s list.  And you will get an AttributeError from python.





Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s