Define a Public Module API with __all__
Core idea
A public API is the set of names you intend callers to use. A leading underscore signals an internal name by convention. A module’s __all__ sequence specifies names included by from module import *; it does not prevent explicit access to other names.
Inspect wildcard exports
In a new empty directory, create the parent folders and these files (an empty file is marked by its filename alone):
bm_tools.py
__all__ = ["total"]label = "box"def total(price, count): return price * countSave the following code as run.py and run python run.py from the new directory. Use a fresh directory for each example.
from bm_tools import *print(total(2, 5))print("label" in globals())Output: 10 and False. The wildcard import uses all, which contains only total. The wildcard form is shown for demonstration; prefer explicit imports.
An internal name is not access control
In a new empty directory, create the parent folders and these files (an empty file is marked by its filename alone):
bm_tools.py
__all__ = []_label = "box"Save the following code as run.py and run python run.py from the new directory. Use a fresh directory for each example.
from bm_tools import _labelprint(_label)Output: box. The explicit import can still access an underscore-prefixed name outside all. Such internal names should not be treated as stable public interfaces.
Re-export an intended package function
In a new empty directory, create the parent folders and these files (an empty file is marked by its filename alone):
bm_shop/__init__.py
from .cost import total__all__ = ["total"]bm_shop/cost.py
def total(price, count): return price * countSave the following code as run.py and run python run.py from the new directory. Use a fresh directory for each example.
from bm_shop import totalprint(total(3, 7))Output: 21. init.py creates the package binding by importing total. all lists it for wildcard imports; the list alone would not create that binding.
Common mistake
all is not a security boundary or an automatic API generator. Define the listed names, document the intended public functions, and use explicit imports in application code.
Practice
Build a small package for parcel totals and label formatting. Re-export one function through init.py, list it in all, and test an explicit import from the package.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Define and use public exports
Check your understanding of public api and all.
A plain module has __all__ = ["total"] and also defines label. Which names are imported by `from module import *`?
What does __all__ guarantee about access to a name outside the list?
How do you expose a function total defined in a submodule cost through the package initializer?
What is a reason to document an intended public API?