Sub topic 7
Packages and __init__.py
This chapter assumes you can write functions and classes, run scripts from a terminal, and import a single module with import and from ... import. It also assumes you know that Python caches imported modules in sys.modules and searches sys.path. Here you will see how a directory becomes a package and what __init__.py does.
What a package is
A module is a single file, such as greet.py. A package is a directory of modules that Python treats as one importable unit. A package can contain other packages, which gives you a tree of dotted names such as shapes.util.mathx.
A package is itself a module object. The import system gives it a __path__ attribute, a list of directories where Python looks for its submodules. A plain module has no __path__. That attribute is how Python tells the two apart.
| Property | Module | Package |
|---|---|---|
| Backed by | One `.py` file | A directory, usually with `__init__.py` |
| Has `__path__` | No | Yes |
| Can contain submodules | No | Yes |
| Code that runs on import | The file | `__init__.py` |
The running example
This chapter uses a small package.
shapes/
__init__.py
circle.py
util/
__init__.py
mathx.pyThe directory shapes is the top-level package. The directory util inside it is a subpackage. The files circle.py and mathx.py are ordinary modules that belong to those packages.
For this to work, the directory that contains shapes/ must be on sys.path. Usually that means you run Python from that directory, or the package is installed. A later chapter covers project layout and installing.
What __init__.py does
A directory with an __init__.py file is a regular package. When you import the package, Python runs __init__.py once. It uses the names the file defines as the package module's namespace.
Importing a package does not import its submodules automatically. Run this from the directory that contains shapes/, with an empty __init__.py:
import shapes
print(shapes.__name__)
print(shapes.__path__)
print(hasattr(shapes, "circle"))The last line prints False. The circle submodule has not been loaded, so no circle attribute exists on the package yet. To get it, import it explicitly:
import shapes.circle
print(hasattr(shapes, "circle"))This prints True. Loading a submodule binds it as an attribute on its parent package. This binding is a side effect of the import system, and it matters later for circular imports.
Common uses of __init__.py
An __init__.py file can be empty, and that is a good default. Add code to it only when you have a reason. The usual reasons are:
- Re-export names from submodules, so users can write
from shapes import circle_area. - Define
__all__to controlfrom shapes import *. - Set up package-level data, such as a version string.
- Import submodules that should always be loaded together.
Here is a version of shapes/__init__.py that re-exports one function:
# shapes/__init__.py
from .circle import area as circle_area
__all__ = ["circle_area"]The leading dot in .circle means "the package that contains this file". With this file in place, import shapes loads shapes.circle as part of running __init__.py. The name circle_area is now an attribute of shapes.
What happens when you import a submodule
Importing shapes.util.mathx is not a single step. Python imports each part of the dotted name from left to right, and each part is cached in sys.modules.
import sys
import shapes.util.mathx
for name in ("shapes", "shapes.util", "shapes.util.mathx"):
print(name, name in sys.modules)All three lines print True. Python ran shapes/__init__.py, then shapes/util/__init__.py, then shapes/util/mathx.py, in that order. A parent package always finishes (or at least begins) loading before its child.
Notice the last step. With import shapes.util.mathx, the only name bound in your code is shapes. You reach the rest through attributes: shapes.util.mathx.square(3). With from shapes.util import mathx, the name bound is mathx.
Imports inside a package
Modules within a package can import each other with absolute or relative imports. This chapter only introduces the idea, and a later chapter compares them in detail. In the example, circle.py needs square from the sibling subpackage:
# shapes/util/mathx.py
def square(x):
return x * x
# shapes/circle.py
from .util.mathx import square
def area(r):
return 3.14159 * square(r)The two dots or one dot count package levels. One dot means the current package, and each extra dot goes up one level. The absolute equivalent is from shapes.util.mathx import square.
Relative imports only work inside a package. If you run circle.py directly as a script, Python does not know its package, and you get ImportError: attempted relative import with no known parent package. Run it as part of the package instead, for example with python -m shapes.circle from the directory that contains shapes/.
Edge cases and pitfalls
Forgetting __init__.py
Since Python 3.3, a directory without __init__.py can still be imported. It becomes a namespace package, a different kind of package that a later chapter covers. If you forget __init__.py by accident, imports often still work, but your package has no place for re-exports, __all__, or setup code. Tools such as test runners and type checkers may also treat the directory differently. Add __init__.py to every package you own.
Heavy code in __init__.py
Everything in __init__.py runs when anyone imports anything from the package, even one small submodule. If it imports large libraries or opens connections, every user pays that cost. Keep it light.
Submodule names that hide package attributes
If __init__.py defines a name that equals a submodule name, one hides the other. Suppose shapes/__init__.py contains circle = 42, and later someone imports shapes.circle. The import system binds the submodule over your value. The result depends on order, which makes the bug hard to find. Give re-exported functions names that differ from submodule names. That is why the example uses circle_area, not circle.
Importing the package name inside itself
Writing import shapes inside shapes/circle.py works, because shapes is already in sys.modules by then. But the package may be only partly initialized. If __init__.py is still running and has not yet defined circle_area, then shapes.circle_area raises AttributeError. Prefer importing from the specific submodule you need.
Inspecting a package
When something goes wrong, print what Python actually loaded:
import shapes
print(shapes.__file__)
print(shapes.__path__)
print(shapes.__package__)__file__ shows which __init__.py ran, which exposes shadowing by a different shapes earlier on sys.path. For a regular package, __package__ is the package's own name.
Summary of the model
A directory with __init__.py is a regular package. Importing it runs __init__.py once and caches the result in sys.modules. Importing a dotted name loads each parent first. A submodule is bound as an attribute on its parent only after it has been imported. Everything the package shows to the outside comes from what __init__.py defines or imports.
Exercise
You run import shapes with an empty shapes/__init__.py, then call shapes.circle.area(2). What happens, and what are two ways to fix it?
Show answer
It raises AttributeError: module 'shapes' has no attribute 'circle', because importing a package does not import its submodules. Fix it by running import shapes.circle (or from shapes import circle) before the call, or by adding from . import circle to shapes/__init__.py so the package loads the submodule itself.
Exercise
After import shapes.util.mathx, which names are bound in your own module's namespace, and which keys are added to sys.modules?
Show answer
Only the name shapes is bound in your namespace. The keys shapes, shapes.util, and shapes.util.mathx are all added to sys.modules. You reach mathx through shapes.util.mathx.