In this lesson, you’ll learn about package initialization. If a file named __init__.py
is present in a package directory, it is invoked when the package or a module in the package is imported. You can use this to execute package initialization code, for example for the initialization of package-level data.
Consider the following __init__.py
file:
print(f'Invoking __init__.py for {__name__}')
alist = ['spam', 'bacon', 'eggs']
Add this file to the pkg
directory from the above example:

Now, when the package is imported, the global list alist
is initialized:
>>> import pkg
Invoking __init__.py for pkg
>>> pkg.alist
['spam', 'bacon', 'eggs']
>>> pkg.mod1
Traceback (most recent call last):
File "<input>", line 1, in <module>
pkg.mod1
AttributeError: module 'pkg' has no attribute 'mod1'
A module in the package can access the global by importing it in turn:
def load_data():
print('loading data using mod1.load_data()')
from pkg import alist
print(f'This is from pkg - {alist}')
class Customer:
pass
Here’s what you get:
>>> from pkg import mod1
Invoking __init__.py for pkg
>>> mod1.load_data()
loading data using mod1.load_data()
This is from pkg - ['spam', 'bacon', 'eggs']
Revert mod1.py
to the previous version by changing load_data()
to no longer use the import
from pkg
:
def load_data():
print('loading data using mod1.load_data()')
class Customer:
pass
You can also use __init__.py
to effect automatic importing of modules from a package. For example, earlier you saw that the statement import pkg
only places the name pkg
in the caller’s local symbol table and doesn’t import any modules. Let’s say that __init__.py
in the pkg
directory contains the following:
print(f'Invoking __init__.py for {__name__}')
import pkg.mod1, pkg.mod2
Then, when you execute import pkg
, modules mod1
and mod2
would be imported automatically:
>>> import pkg
Invoking __init__.py for pkg
>>> pkg.mod1.load_data()
loading data using mod1.load_data()
>>> x = pkg.mod2.Location()
>>> x
<pkg.mod2.Location object at 0x10e1c2dd8>
Note: Much of the Python documentation states that an __init__.py
file must be present in the package directory when creating a package. This was once true. It used to be that the very presence of __init__.py
signified to Python that a package was being defined. The file could contain initialization code or even be empty, but it had to be present.
Starting with Python 3.3, Implicit Namespace Packages were introduced. These allow for the creation of a package without any __init__.py
file. Of course, it can still be present if package initialization is needed. But it is no longer required.
jeffwashcloth on May 13, 2020
What is the environment used in these videos? It’s pretty nifty, with its own file explorer, interpreter, and editor.