liveBook · Manning

__init__.py

As explained in Python Workout, Second Edition

__init__.py is a conventional Python package file whose code is executed when the containing package is imported.

Use __init__.py to make a directory a Python package and control what happens when that package is imported. Python executes the file, where it can import modules such as first.py and expose their contents through the package. section 9.9

Choose an import form based on the name you want available:

  • from mypackage import first makes first available directly. section 9.9
  • import mypackage.first keeps the fully qualified module name. section 9.9
  • import mypackage loads and executes mypackage/__init__.py. section 9.9

Package layout

Place first.py, second.py, and third.py in mypackage, add __init__.py, and ensure the directory is on sys.path. Importing mypackage can then initialize the package and import selected internal modules. section 9.9

import mypackage

Inspect the minimal package import form that triggers __init__.py. section 9.9

How Python Workout, Second Edition covers it

How deep it goes
Explains package recognition, initialization, and module imports, but does not detail execution order or advanced package configuration.
Examples
Uses mypackage with first.py, second.py, third.py, and alternative import statements.
What it assumes
Assumes familiarity with Python modules and sys.path while explaining package initialization from the import behavior upward.
What you can do after
Build it from scratch by organizing modules into a package and selecting direct or qualified import forms.
How it connects
Connects Python modules, packages, imports, sys.path, distribution packages, and setup.py.

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 Python Workout, Second Edition. The section links point to the parts of the book it draws on.