Python - Package __init__.py Files

Introduction

Each directory named within the path of a package import statement should contain a file named __init__.py.

Consider the following import statement:

import dir1.dir2.mod 

Both dir1 and dir2 must contain a file called __init__.py.

The container parent directory (dir0) for dir1 does not require such a file because it's not listed in the import statement itself.

For a directory structure such as this:

dir0\dir1\dir2\mod.py 

and an import statement of the form:

import dir1.dir2.mod 

The following rules apply:

  • dir1 and dir2 both must contain an __init__.py file.
  • dir0, the container, does not require an __init__.py file; this file will simply be ignored if present.
  • dir0, not dir0\dir1, must be listed on the module search path sys.path.

You would have something like:

dir0\                     # Container on module search path 
    dir1\ 
        __init__.py 
        dir2\ 
            __init__.py 
            mod.py 

__init__.py

The __init__.py files can contain Python code, just like normal module files.

Their code is run automatically the first time a Python program imports a directory.

They perform initialization steps required by the package.

These files can also be completely empty.

Related Topic