Sub topic 10
Designing a package's public interface with `__all__`
This chapter assumes you can build a package with __init__.py files, write relative imports, and know that import caches modules in sys.modules. Here you decide which names a package offers to its users and how __all__ takes part in that decision.
What a public interface is
Every module and package exposes many names, but only some are meant for outside use. The rest are implementation details you want to be free to rename or delete. The public interface is the set of names you promise to keep stable.
Python has no access modifiers, so this promise is made through conventions and a few mechanisms:
- A leading underscore (
_helper) marks a name as private by convention. - Re-exporting a name in
__init__.pymakes it reachable aspackage.name. __all__lists the names thatfrom module import *imports. It also documents the interface for readers and tools.
None of these stop a determined user from writing shapes.circle._validate(3). They tell users which names are safe to depend on.
The running example
This chapter uses the shapes package from earlier. The files are:
shapes/
__init__.py
circle.py
util/
__init__.py
mathx.pyHere is the code for the two modules that do the work:
# shapes/util/mathx.py
def square(x):
return x * x
# shapes/circle.py
from .util.mathx import square
__all__ = ["area"]
PI = 3.14159
def _check_radius(r):
if r < 0:
raise ValueError("radius must be non-negative")
def area(r):
_check_radius(r)
return PI * square(r)circle.py has four module-level names: square, PI, _check_radius, and area. Only area is part of the module's interface, and __all__ says so.
What `__all__` does
__all__ is a list of strings assigned at module level. It affects one thing at runtime: which names from module import * binds. Without __all__, a star import binds every name in the module's namespace that does not start with an underscore. That includes names you imported, such as square, and constants such as PI.
| Situation | Names bound by `from circle import *` |
|---|---|
| No `__all__` | `square`, `PI`, `area` (and any other non-underscore names) |
| `__all__ = ["area"]` | `area` only |
| `__all__ = ["area", "_check_radius"]` | `area` and `_check_radius`, because `__all__` overrides the underscore rule |
Three points follow from this.
__all__does not hide anything.from shapes.circle import PIandshapes.circle.PIboth still work.__all__does not change whatimport shapes.circleorfrom shapes.circle import areado.- A name listed in
__all__that does not exist raisesAttributeErrorwhen someone runs the star import. A typo in__all__therefore stays hidden until a star import runs.
Building the package's front door
A user should not need to know that area lives in circle.py. Their code would break if you later moved it. The package's __init__.py re-exports what you want to offer:
# shapes/__init__.py
from .circle import area as circle_area
__all__ = ["circle_area"]Now this script, run from the directory that contains shapes/, works:
# demo.py
from shapes import *
print(circle_area(2))
print("area" in globals())The first line prints 12.56636. The second prints False, because the star import bound only circle_area. The package renamed the function on the way out. That is a design choice: area is clear inside circle.py, but circle_area is clear at the package level, where several shape modules might each have an area.
The inner file circle.py also declares its own __all__. That is not redundant. It controls from shapes.circle import * and documents that module separately from the package.
Submodules and `__all__` in a package
Star-importing a package behaves differently from star-importing a plain module in one respect. Python reads __all__ from shapes/__init__.py. Submodules are not imported automatically by a star import. If you list a submodule name in __all__, Python imports it and binds it:
# shapes/__init__.py
from .circle import area as circle_area
__all__ = ["circle_area", "util"]With this version, from shapes import * also binds util, the subpackage. Without a listed name, a star import of a package without __all__ only binds names already present in shapes/__init__.py's namespace. A submodule that something else has already imported is in that namespace, because importing shapes.circle sets circle as an attribute of shapes. This makes the result of a star import depend on what has been imported elsewhere. Defining __all__ makes it predictable.
Should you use star imports at all?
Mostly no. Star imports make it unclear where a name came from, and they can silently overwrite names you defined earlier. Style guides such as PEP 8 discourage them in application code. They are acceptable in two cases:
- An interactive session, where convenience matters more than clarity.
- An
__init__.pythat republishes a submodule, such asfrom .circle import *. This works well when the submodule defines__all__, because the package then inherits exactly that list.
The second case is a good reason to write __all__ in every module. The package's interface is then assembled from the interfaces of its parts:
# shapes/__init__.py
from .circle import *
from . import circle
__all__ = circle.__all__ + []Here circle.__all__ is ["area"], so the package exposes area. Adding more submodules means extending the concatenation. Keep the list explicit when it is short. Computed lists are harder for readers and tools to follow.
Tools and re-exports
Static type checkers and linters usually treat an import in __init__.py as private unless you mark it as a re-export. Two forms count as re-exports:
- The name appears in
__all__. - The import uses the redundant alias form,
from .circle import area as area.
If you rely on re-exports without either marker, a type checker may report the name as not exported, even though it works at runtime. Listing it in __all__ fixes that and serves as documentation as well.
Keeping the interface stable
A few habits keep the interface under control as the package grows:
- Keep
__all__as a plain list literal of strings. Tools read it statically, and dynamic construction can defeat them. - Keep it sorted or grouped. Reviewers then see added or removed names at a glance.
- Treat removing a name from
__all__as a breaking change, even though the name is still importable. - Put internal helpers in modules with an underscore prefix, such as
_internal.py, so their status is visible in the import path. - Document the public names in the package docstring or README. A test that imports each name in
__all__catches typos early.
Such a test needs no framework:
# check_api.py
import shapes
missing = [name for name in shapes.__all__ if not hasattr(shapes, name)]
assert not missing, f"names in __all__ are not defined: {missing}"
print("public interface OK")This script prints public interface OK for the shapes package as written in the first __init__.py version. Run it as part of your test suite and a misspelled entry fails the build.
Exercise
A module stats.py defines mean, median, _cache, and an imported name Counter. It has no __all__. What does from stats import * bind? Then, what changes if you add __all__ = ["mean", "median"], and can a user still call stats._cache?
Show answer
Without __all__, the star import binds every name that does not start with an underscore: mean, median, and Counter. _cache is skipped. With __all__ = ["mean", "median"], it binds only mean and median, so Counter is no longer bound. A user can still reach stats._cache by writing import stats and then stats._cache, because __all__ affects only star imports and does not make names inaccessible.
Exercise
In shapes/__init__.py you write __all__ = ["circle_area", "sqare"] (a typo for a submodule). What happens at from shapes import *, and what simple check catches this before release?
Show answer
Python raises an AttributeError because shapes has no attribute sqare and no submodule of that name. The error appears only when someone runs the star import. A test that loops over shapes.__all__ and checks hasattr(shapes, name), like check_api.py above, catches it before release.