Skip to content

__init__.py

In Python, an __init__.py file marks the directory that contains it as a regular package and holds the code that runs when you import that package. Its name follows the dunder convention Python uses to flag names with special meaning to the language.

Python executes the file implicitly the first time the package is imported, and every name it defines becomes an attribute of the package. That makes it the natural place to shape a package’s public interface, so a class in a submodule can be imported straight from the top level. It’s also where you set __all__, the list of public names that a wildcard import pulls in.

An empty __init__.py is valid and common, because its presence alone identifies the directory as a package. Since Python 3.3, the file isn’t strictly required: a directory without one can still be imported as a namespace package, an advanced feature for packages spread across several directories. Despite the shared name, the file has nothing to do with the __init__() method.

Example

Say you’re building a store package whose Cart class lives in store/cart.py, and you’d like people to import it straight from store:

Language: Python Filename: store/__init__.py
"""Shopping cart tools."""

from store.cart import Cart

__all__ = ["Cart"]

Importing the package runs that file, which binds Cart in the package’s own namespace:

Language: Shell
$ python -c "from store import Cart; print(Cart)"
<class 'store.cart.Cart'>

Without the import line in __init__.py, the same command fails with an ImportError, and you’d have to import it from the submodule yourself with from store.cart import Cart.

Toggle between an empty store/__init__.py, a bare re-export of Cart, and the full version above with __all__ to see what each one leaves in the package namespace and which imports then work:

Interactive diagram — enable JavaScript to view.
What Is Python's __init__.py For?

Tutorial

What Is Python's __init__.py For?

Learn to declare packages with Python's __init__.py, set package variables, simplify imports, and understand what happens if this module is missing.

basics python

For additional information on related topics, take a look at the following resources:

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Martin Breuss • Updated Sept. 27, 2026