Lesson · Modules, Packages & Imports
Packages
55 min readPackages
Packages organize modules into importable namespaces. Good package boundaries expose a deliberate public API while keeping internal structure changeable.
Learning goals
- Explain how a directory becomes an importable package and what
__init__.pychanges about that. - Read a dotted import path and say which package, subpackage, and module it touches.
- Re-export a name from a submodule so callers import from the package, not its internals.
- Predict which files run when
import calculatorexecutes versusimport calculator.formats. - Choose between absolute and relative imports inside a package and justify the choice.
Mental model
The directory tree is the namespace tree: calculator.formats.pretty names the module pretty.py inside the subpackage formats inside the package calculator. Importing any node runs the __init__.py files along the way, top down, and the package initializer is the place to decide which names belong to the public surface. Subpackages simply repeat the same rules one level deeper.
Mental model
read it top to bottom
calculator/ the package
├── __init__.py runs on first import; curates the public surface
├── core.py a module: calculator.core
└── formats/ a subpackage: a package inside a package
└── __init__.pyCore idea
A package is a directory that the import system treats as a namespace: each module inside becomes a dotted suffix of the package name, and each __init__.py along the path runs once when that subtree is first imported. The package initializer is where you choose what the package promises, by re-exporting a few names and leaving the rest internal. Package design is therefore about dependency direction and a stable public surface, not about file layout for its own sake.
Package directories
A package groups importable modules under a shared namespace. Modern Python can support namespace packages without __init__.py, while regular packages commonly include it.
__init__.py
__init__.py initializes a regular package and can expose a curated public surface. Keep it lightweight to avoid expensive or circular import-time behavior.
Subpackages
A subpackage is a package nested inside another package, such as calculator/formats/ inside calculator/. Its modules are imported through the full dotted path (for example calculator.formats.pretty), and its __init__.py, when present, runs the first time the subpackage is imported.
Absolute imports
An absolute import names a package from the import root, which makes dependency direction explicit. It is usually the clearest style across package boundaries.
Relative imports
A relative import uses leading dots to refer to the current package hierarchy. It is useful inside a package but depends on the module being loaded with package context.
Public APIs
A public API is the set of names callers are encouraged to depend on. Re-export deliberate entry points and treat internal module structure as changeable implementation detail.
Package organization
Organize packages around cohesive responsibilities and dependency direction rather than arbitrary file size. Public imports should remain stable even if internal modules later move.
Walkthrough
- The comment block shows the physical layout:
calculator/is the package,core.pyandformats.pyare modules inside it, and__init__.pyruns first whencalculatoris imported. from .core import addin__init__.pyis a relative import: the dot means "the package this file belongs to", so it reaches the sibling modulecore.py, executes it, and binds itsaddfunction into thecalculatornamespace.__all__ = ["add"]declares thataddis the public name; it documents intent and controls what a wildcardfrom calculator import *picks up, whilecoreandformatsremain reachable but internal.- Predict before running: which files execute under
import calculator, whethercalculator.addandcalculator.core.addare the same function, and whetherformats.pyhas run yet.
Experiments to try
- Build the package on disk and print
calculator.add(2, 3)andcalculator.core.add(2, 3); useisto confirm both names reach the same function object. - Add
print(__name__)to__init__.pyandcore.py, importcalculator, and note the order the messages appear in. - Add
import calculator.formatsafter a plainimport calculatorand explain the extra execution it triggers. - Rename
core.pytoarithmetic.pyand update only the relative import; show thatfrom calculator import addkeeps working while the internal filename changed.
Common mistakes
- Forgetting that importing a package does not import its submodules:
import calculatorruns__init__.pyand whatever it imports, butcalculator.formatsis not loaded until something asks for it, so attribute access can raiseAttributeError. - Putting heavy or circular logic in
__init__.py: every import of any submodule executes the package initializer first, so a slow or cycle-inducing top level taxes all imports and can fail before the submodule is reached. - Importing internals from outside the package (
from calculator.core import add): callers become tied to a file name you wanted to keep movable, while the published pathcalculator.addis the one you can maintain. - Using a relative import in a file meant to be run directly: relative imports need package context, so
python calculator/core.pyfails with "attempted relative import with no known parent package".
Practice: Easy
- Create the worked example's tree with an
addfunction incore.pyand even an emptyformats.py; then runimport calculatorin the REPL and printcalculator.add(2, 3). - Print
calculator.__name__andcalculator.core.__name__after importing; state how the dotted names relate to the directory tree. - Add a
printtoformats.pyand confirm it does not appear afterimport calculatoralone; importcalculator.formatsand check again.
Practice: Medium
- Add
multiplytocore.pyand leave it out of__all__; comparefrom calculator import *with an explicitfrom calculator import multiplyand explain the difference. - Create the
formats/subpackage with its own__init__.pyand apretty.pymodule; importcalculator.formats.prettyand print the loaded module's full dotted name. - Change the relative import in
__init__.pyto an absolutefrom calculator.core import add; rename the top-level package directory and state which style survives the rename.
Practice: Hard
- Restructure a flat one-file script into a package with an
__init__.pyexposing two public names; verifyfrom package import nameworks for both and that the calling code never mentions an internal module. - Add a subpackage with its own
__init__.pyand an__all__list; prove withfrom subpackage import *which names leak, and show that an unlisted name stays hidden but remains reachable by explicit import. - Rename two internal modules inside an existing package, update only the package's
__init__.py, and rerun the unchanged calling code; explain which imports would have broken without the re-export layer.
Lesson checklist
- I can turn a directory into a package and explain what
__init__.pycontrols. - I can read a dotted import path and map it onto the directory tree.
- I can re-export chosen names so callers depend on
calculator.add, notcalculator.core.add. - I can explain why importing a package does not load all of its submodules.
Remember
A package maps a directory tree onto dotted import names, and each `__init__.py` along the path runs once when that subtree is first imported. Use the package initializer to publish a small surface (re-exports plus `__all__`) and keep it lightweight, because every submodule import pays for it. Subpackages repeat the same rules one level deeper, and callers should depend on the published names rather than internal file paths.
Interview angles
What is the main purpose of **Package directories**?+
A package groups importable modules under a shared namespace. Modern Python can support namespace packages without __init__.py, while regular packages commonly include it.
What should you pay attention to when using **__init__.py**?+
__init__.py initializes a regular package and can expose a curated public surface. Keep it lightweight to avoid expensive or circular import-time behavior.
How does **Subpackages** fit into this lesson?+
A subpackage is a package nested inside another package, such as calculator/formats/ inside calculator/. Its modules are imported through the full dotted path, and its __init__.py, when present, runs the first time the subpackage is imported.
Why can `import calculator` succeed while `calculator.formats` raises `AttributeError`?+
Importing a package runs its __init__.py and whatever that file imports, but not every submodule. formats is only loaded when something imports calculator.formats (or __init__.py re-exports it), so import the submodule before reaching into it.