Packages
Python provides a very straightforward packaging system, which is simply anextension of the module mechanism to a directory.
Any directory with an init.py
file is considered a Python package.The different modules in the package are imported in a similar manner as plainmodules, but with a special behavior for the init.py
file, which isused to gather all package-wide definitions.
A file modu.py
in the directory pack/
is imported with thestatement import pack.modu
. This statement will look for aninit.py
file in pack
and execute all of its top-levelstatements. Then it will look for a file named pack/modu.py
andexecute all of its top-level statements. After these operations, any variable,function, or class defined in modu.py
is available in the pack.modunamespace.
A commonly seen issue is to add too much code to init.py
files. When the project complexity grows, there may be sub-packages andsub-sub-packages in a deep directory structure. In this case, importing asingle item from a sub-sub-package will require executing allinit.py
files met while traversing the tree.
Leaving an init.py
file empty is considered normal and even a goodpractice, if the package’s modules and sub-packages do not need to share anycode.
Lastly, a convenient syntax is available for importing deeply nested packages:import very.deep.module as mod
. This allows you to use mod in place of theverbose repetition of very.deep.module
.