liveBook · Manning

__init__.py

As explained in The Quick Python Book, Fourth Edition

An __init__.py file is a Python package file that can contain initialization code executed when the package is imported.

Place an __init__.py file in a directory to mark it as a Python package. The file can be empty. Although it is optional for package recognition, including it helps prevent directories of miscellaneous Python code from being imported as packages. Python executes it the first time the package or subpackage is loaded. section 18.3.1

Initialize a package

Suppose mathproj/__init__.py contains `print("Hello from mathproj init")` and `version = 1.03`. In a fresh Python session, `import mathproj` prints the message; `mathproj.version` then evaluates to `1.03`. Names assigned in the file become attributes of the package. section 18.3 section 18.3.2

Importing a package does not automatically load every subpackage or module beneath it. Import a nested module explicitly, or arrange the needed imports in an __init__.py file. Before a nested module loads, Python loads its parent packages and runs their initialization files. section 18.3.3 section 18.7

import mathproj.comp.numeric.n1
 
Hello from mathproj.comp init
Hello from numeric init
 
mathproj.comp.numeric.n1.g()
 
version is 1.03
Called function h in module n2

The nested import prints messages from the parent subpackages’ initialization files before the module’s function is called. section 18.3.3

An __init__.py file can also define `__all__`, a list of names selected by `from package import *`. For example, `__all__ = ['comp']` selects `comp` from mathproj; it does not recursively import names from comp. Without `__all__`, a wildcard import from the package imports no names. Prefer explicit imports when the origin of names matters. section 18.4 section 10.3

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains first-load execution, package attributes, nested imports, and __all__ through examples, without detailing import machinery internals.
Examples
Demonstrates initialization messages, a package version attribute, nested imports, and wildcard imports with a small package tree.
What it assumes
Assumes familiarity with Python modules and imports while showing how to create package directories and files.
What you can do after
Build it from scratch: create an empty or populated __init__.py, then choose explicit imports or __all__ for package access.
How it connects
Connects __init__.py to packages, subpackages, modules, namespaces, import statements, and __all__.

Also explained in

Compare how 4 books explain __init__.py →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.