Sub topic 3
Designing a Python Package’s Public Interface
Assume you know basic Python syntax, can run scripts, and understand files and directories. This chapter focuses on how package structure affects imports.
Exports and `__all__`
A package’s public interface is the set of names it promises users can import. Define that interface in __init__.py:
# shapes/__init__.py
from .circle import area as circle_area
__all__ = ["circle_area"]__all__ controls names imported by from shapes import *. It also documents intended exports. It does not prevent users from importing other existing submodules.
Run a module from its package context with:
python -m shapes.toolsPython sets the module’s package information correctly, so relative imports work. Prefer python -m when a module belongs to a package. Keep executable behavior behind an if __name__ == "__main__": guard.
Layout and installation
A typical project uses a source directory:
project/
pyproject.toml
src/
shapes/
__init__.py
circle.pyInstalling the project, often with python -m pip install -e ., makes shapes importable from other working directories. The editable option points Python at your development files.
Errors and side effects
Circular imports happen when module A imports B while B imports A. One module may then see a partially initialized module. Move shared definitions into a third module, or defer one import until it is needed:
def total(order):
from customers import discount_for
return order["amount"] - discount_for(order["customer"])Avoid files whose names shadow standard or installed modules, such as json.py or typing.py. Import-time side effects, such as network calls or database writes at module top level, also make imports slow and unpredictable. Put actions in functions.
Import machinery and advanced forms
Python first checks sys.modules, its cache. Otherwise, finders search locations in sys.path, and loaders create and execute a module object. importlib exposes this process:
import importlib
name = "json.decoder"
module = importlib.import_module(name)
print(module.__name__)Namespace packages can span directories without an __init__.py. They are useful for separately distributed portions of one package name, but regular packages are often simpler for small projects. importlib.reload(module) re-executes a module, but existing references and objects may still point to old definitions.
Exercise
Why can moving a shared function into a third module fix a circular import?
Show answer
Both original modules can import the third module without importing each other, removing the cycle.