ZetCode

Python __init__.py file

last modified November 29, 2026 Python 3.15

In this article we look at the __init__.py file. We show what its presence changes, when its code runs, how it defines the public interface of a package, and which work does not belong in it.

Packages and modules in general are covered in Python package and Python module. Directories without an __init__.py file are explained in Python namespace packages.

The file that makes a regular package

A directory with an __init__.py file inside is a regular package. Since Python 3.3 the file is not required for an import to work; a directory without it can still be imported as a namespace package. The file is what turns the directory into a regular package with a single location and a place for initialization code.

project/
.
├── main.py
└── utils/
    └── __init__.py

The package is imported in the usual way. A comment-only file is enough to mark the directory as a regular package.

utils/__init__.py
# This file makes utils a regular package.

The main.py program prints what the package object knows about itself. __file__ is the path of this file, __path__ is the list of directories the package is searched in, and the package itself is a module object.

main.py
import os
import utils

print(os.path.relpath(utils.__file__))
print([os.path.relpath(p) for p in utils.__path__])
print(type(utils).__name__)

A regular package has one directory in __path__ and a real __file__. Both differ in a namespace package, where __file__ is None and __path__ can hold several directories.

$ python main.py
utils/__init__.py
['utils']
module

The file is a module

The __init__.py file is executed as the module that represents the package, so everything defined in it becomes an attribute of the package. A docstring documents the package and a version string is a common addition.

utils/__init__.py
"""Small text helpers."""
__version__ = '0.3.0'


def shout(text):
    return text.upper()

The package has a docstring, a version, and a function. The function lives in __init__.py itself, while count_words is added in a new text submodule.

utils/text.py
def count_words(text):
    return len(text.split())

Importing the submodule also sets it as an attribute of the package, which is why utils.text works after import utils.text. The program reads the attributes defined in __init__.py and calls both functions.

main.py
import utils
import utils.text

print(utils.__name__)
print(utils.__doc__)
print(utils.__version__)
print(utils.shout('hi'))
print(utils.text.count_words('a b c'))

The package name is utils and its docstring is the first string in __init__.py. The two functions return their results without knowing which file they were defined in, because the package namespace hides that detail from the caller.

$ python main.py
utils
Small text helpers.
0.3.0
HI
3

Initialization code runs once

All code in __init__.py runs when the package is imported for the first time. Importing a submodule imports its parent package first, so the initialization happens before the submodule's code. Later imports reuse the module already stored in sys.modules and do not run it again.

project/
.
├── main.py
└── shop/
    ├── __init__.py
    ├── orders.py
    └── users.py

The shop package builds a small catalog when it is initialized and prints a message so that the moment is visible in the output.

shop/__init__.py
print('initializing shop')

catalog = {'apple': 1.2, 'pear': 0.8}

The orders module uses the catalog through a relative import, and users is independent of it. The program imports the package and both submodules.

shop/orders.py
from . import catalog


def price(item):
    return catalog[item]

The leading dot in from . import catalog means the current package; the full topic is in Python relative imports. The next listing also defines the users module and the program.

shop/users.py
def login(name):
    return f'{name} logged in'

Three imports follow each other, but the initialization message appears only once: it is printed during the first import, before either submodule is available.

main.py
import shop
from shop import users
from shop.orders import price

print(shop.catalog)
print(price('pear'))
print(users.login('Alice'))

The package object holds the catalog after initialization, so shop.catalog works without a submodule named catalog. The other two functions come from separate modules and use the same package state.

$ python main.py
initializing shop
{'apple': 1.2, 'pear': 0.8}
0.8
Alice logged in

Re-exporting the public interface

A common use of __init__.py is to import names from submodules and expose them at the package level. Users then write from textkit import normalize instead of from textkit.clean import normalize, and the internal file layout can change without breaking their code.

textkit/clean.py
def normalize(text):
    return ' '.join(text.split())


def slugify(text):
    return '-'.join(text.lower().split())

The module defines two functions. Only normalize is imported into the package for now.

textkit/__init__.py
"""Small text toolkit."""
from .clean import normalize

The relative import copies the function into the package namespace. Its __module__ attribute still points to the module where it was defined, which the program prints together with the package's own names.

main.py
import textkit

print(textkit.normalize('  Hello   there  '))
print(textkit.normalize.__module__)
print(sorted(k for k in vars(textkit) if not k.startswith('__')))

The function collapses the extra spaces, and __module__ reveals that it comes from textkit.clean. The package namespace contains the submodule as clean and the function as normalize.

$ python main.py
Hello there
textkit.clean
['clean', 'normalize']

__all__ and star imports

__all__ is a list of names that from package import * copies. It affects only the star form. The names still exist as attributes of the package, and an explicit from package import name works regardless of the list.

textkit/__init__.py
"""Small text toolkit."""
from .clean import normalize, slugify

__all__ = ['normalize']

Both functions are now imported into the package, but only normalize is listed in __all__. The star import in the program brings in one name; the second function is reached through the package object.

main.py
from textkit import *

print(normalize('  Hello   there  '))
print('slugify' in globals())

import textkit
print(sorted(textkit.__all__))
print(textkit.slugify('Hello There'))

slugify is missing from the global namespace, yet it is present on the package and can be called. This is why __all__ documents the public API but cannot hide anything: it only controls what the wildcard import copies.

$ python main.py
Hello there
False
['normalize']
hello-there

Lazy exports with module __getattr__

A module-level __getattr__ function, added by PEP 562 in Python 3.7, is called when an attribute is not found in the package. It can import a submodule on first access and store the result in the package namespace, so the import cost is paid only when the name is actually used.

report/summary.py
def summarize(numbers):
    mean = sum(numbers) / len(numbers)
    return f'{len(numbers)} values, mean {mean:.1f}'

The summary module is simple, but the same pattern is used for modules that are slow to import, such as ones that load large data files.

report/__init__.py
"""Report package."""


def __getattr__(name):
    if name == 'summary':
        print('loading report.summary')
        from .summary import summarize
        globals()['summary'] = summarize
        return summarize
    raise AttributeError(f'module {__name__!r} has no attribute {name!r}')

The function imports the submodule when summary is asked for, stores the function under that name, and raises AttributeError for any other unknown name, as a package normally would. The program prints markers before and after the first access.

main.py
import report

print('before')
print(report.summary([1, 2, 3, 4]))
print('after')
print(report.summary([10, 20]))

The loading message appears between before and the result. The second call uses the cached function and does not import or print again.

$ python main.py
before
loading report.summary
4 values, mean 2.5
after
2 values, mean 15.0

Keeping a split package regular with extend_path

Regular packages live in one directory, so they cannot be split across locations by themselves. pkgutil.extend_path is the older technique that lets several directories contribute to the same regular package. Native namespace packages do the same without an __init__.py file and are the better choice for new code; this section shows the older form because it is still found in installed packages.

project/
.
├── main.py
└── ext/
    ├── a/
    │   └── mypkg/
    │       ├── __init__.py
    │       └── left.py
    └── b/
        └── mypkg/
            ├── __init__.py
            └── right.py

Both mypkg directories contain the same __init__.py. It extends the package's own path with every other mypkg directory found on sys.path.

ext/a/mypkg/__init__.py
from pkgutil import extend_path

__path__ = extend_path(__path__, __name__)

The two modules provide one function each, and both directories are added to sys.path before the import. The copy in ext/b/mypkg/__init__.py is identical.

ext/a/mypkg/left.py
def side():
    return 'left'

The second module has the same small function under a different name, which returns 'right'.

ext/b/mypkg/right.py
def side():
    return 'right'

The program imports both modules and prints the resulting package path.

main.py
import os
import sys

sys.path.extend(['ext/a', 'ext/b'])

import mypkg
import mypkg.left
import mypkg.right

print([os.path.relpath(p) for p in mypkg.__path__])
print(mypkg.left.side(), mypkg.right.side())

The package is still regular: __file__ points to the first __init__.py and __path__ is a plain list. Unlike a namespace package, the initialization code runs and the package has a docstring, but the list now contains both directories.

$ python main.py
['ext/a/mypkg', 'ext/b/mypkg']
left right

When the package fails at import

Because the file runs before anything inside the package is available, an error in it makes every import of the package fail, including imports of submodules that do not need the failing code. This example raises an error on purpose.

badpkg/__init__.py
raise RuntimeError('badpkg needs settings.toml')

The submodule itself is valid and does not depend on the missing file. The program catches the error to show what happens with both import forms.

badpkg/core.py
def run():
    return 'ok'

The first import fails with the error from __init__.py. The second one tries a submodule, but Python imports the parent package first, so it fails in the same place.

main.py
try:
    import badpkg
except RuntimeError as e:
    print(type(e).__name__, e)

try:
    import badpkg.core
except RuntimeError as e:
    print('submodule too:', type(e).__name__)

A failed import is not cached, so the second attempt runs __init__.py again and raises again. Work that can fail, such as reading a configuration file or connecting to a service, belongs in an explicit function, not at import time.

$ python main.py
RuntimeError badpkg needs settings.toml
submodule too: RuntimeError

What belongs in __init__.py

The file is best kept small and predictable. The following rules follow from the examples above.

Source

Packages – Python Tutorial

Regular packages – The import system

PEP 562 – Module __getattr__ and __dir__

pkgutil.extend_path – Python documentation

In this article we have seen that __init__.py turns a directory into a regular package, runs once at import, defines package attributes and the public API, and can defer submodule imports. See also Python package, Python namespace packages, Python relative imports, and Python module.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.