Featurecore
Packages
Also called package, __init__.py, regular package, subpackage, submodule, dotted module names, __path__.
A package is a module that holds other modules. A regular package is a directory with an __init__.py file, and its submodules have dotted names such as sound.effects.echo.
- Language
- Python
Synopsis
sound/ # the package sound
__init__.py # runs when sound is imported
effects/ # the subpackage sound.effects
__init__.py
echo.py # the module sound.effects.echo
import sound.effects.echo # runs sound/__init__.py, then effects/__init__.py, then echo.py
sound.effects.echo.echofilter(...) # use the full name
from sound.effects import echo # bind echo
from sound.effects.echo import echofilter
Semantics
r1. "Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A."1 A package is a module: "all packages are modules, but not all modules are packages. Or put another way, packages are just a special kind of module. Specifically, any module that contains a path attribute is considered a package."2 Example: attributes.
r2. "A regular package is typically implemented as a directory containing an init.py file. When a regular package is imported, this init.py file is implicitly executed, and the objects it defines are bound to names in the package’s namespace."2 An import of a submodule runs the files of all the packages above it: "Importing parent.one will implicitly execute parent/init.py and parent/one/init.py."2 Example: init-runs.
r3. The __init__.py file decides what is a package. "The init.py files are required to make Python treat directories containing the file as packages (unless using a namespace package, a relatively advanced feature). This prevents directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path."1 "A subdirectory inside a regular package that does not contain an init.py file is treated as an implicit namespace package (a “namespace subpackage”) rooted in that parent."2 Example: no-init.
r4. After import sound.effects.echo, the submodule "must be referenced with its full name."1 With import item.subitem.subsubitem, "each item except for the last must be a package; the last item can be a module or a package but can’t be a class or function or variable defined in the previous item."1 Example: not-a-package.
r5. An import of a package does not import its submodules. When a submodule is loaded, Python binds it in the parent: "after importing spam.foo, spam will have an attribute foo which is bound to the submodule."2 sys.modules holds every level: "if foo.bar.baz was previously imported, sys.modules will contain entries for foo, foo.bar, and foo.bar.baz."2 Example: attributes.
r6. __path__ is "A (possibly empty) sequence of strings enumerating the locations where the package’s submodules will be found. Non-package modules should not have a path attribute."3 __package__ is "the name of the module’s package (which can be equal to module.name if the module itself is a package)."3 Example: attributes.
r7. An __init__.py file can import from its submodules to give the package a short public interface. The reference shows from .foo import Foo in spam/__init__.py, which "puts name bindings for foo and Foo in the spam module".2 Example: facade.
Examples
Each __init__.py runs once, before the module below it (rule r2). The second import runs nothing.
print("init sound")
print("init sound.effects")
print("load sound.effects.echo")
def echofilter(text):
return text + " " + text[-2:]
import sound.effects.echo
import sound.effects.echo
print(sound.effects.echo.echofilter("hello"))
init sound
init sound.effects
load sound.effects.echo
hello lo
import sound does not load sound.effects (rule r5). After the submodule is loaded, it is an attribute of its parent, and sys.modules has all three names. Only the packages have __path__ (rules r1 and r6).
"""The sound package."""
"""Sound effects."""
def echofilter(text):
return text + " " + text[-2:]
import os
import sys
import sound
try:
sound.effects
except AttributeError:
print("sound.effects is not loaded")
from sound.effects import echo
print(sound.effects.echo is echo)
print(echo.__name__, echo.__package__)
print(hasattr(sound, "__path__"), hasattr(echo, "__path__"))
print([os.path.relpath(p) for p in sound.effects.__path__])
print(sorted(n for n in sys.modules if n.startswith("sound")))
sound.effects is not loaded
True
sound.effects.echo sound.effects
True False
['sound/effects']
['sound', 'sound.effects', 'sound.effects.echo']
sound/effects/__init__.py imports echofilter from its submodule, so users can call sound.effects.echofilter (rule r7). The import also binds echo in the package.
"""The sound package."""
from .echo import echofilter
def echofilter(text):
return text + " " + text[-2:]
import sound.effects
print(sound.effects.echofilter("hi"))
print(sound.effects.echo.__name__)
hi hi
sound.effects.echo
The last part of a dotted import must be a module, not a function (rule r4).
"""The sound package."""
def echofilter(text):
return text + " " + text[-2:]
This code raises ModuleNotFoundError, on purpose.
import sound.echo.echofilter
Use from sound.echo import echofilter to bind the function.
The examples give the same output on CPython 3.12.3, 3.13.14 and 3.14.6.
Pitfalls
A forgotten __init__.py
A subdirectory without __init__.py does not cause an error (rule r3). It becomes a namespace package, which has no __init__.py code to run and no __file__.
"""The sound package."""
NAME = "karaoke"
This code runs but gives a wrong answer on purpose.
import sound.filters.karaoke
print(sound.filters.karaoke.NAME)
print(sound.filters.__file__)
karaoke
None
Add sound/filters/__init__.py when the directory is meant to be a regular package.
Slow or noisy code in __init__.py
The __init__.py files of all parent packages run before any submodule (rule r2). A slow import or a print in sound/__init__.py affects every user of every submodule. Keep __init__.py short.
import package and then package.submodule
import sound followed by sound.effects fails with AttributeError unless some code loaded sound.effects before (rule r5), as in attributes. Import the submodule that you use, or import it in __init__.py as in facade.
Comparison
Java packages also have dotted names, but the hierarchy gives no access rights: "there is no special access relationship between a package named oliver and another package named oliver.twist".4 In Python, an import of sound.effects always runs sound/__init__.py first (rule r2).
Rust builds a tree of modules from mod declarations in the crate. For a submodule mod vegetables; declared in src/garden.rs, the compiler looks "In the file src/garden/vegetables.rs" or "In the file src/garden/vegetables/mod.rs".5 Python finds subpackages from the directories alone.
Implementation notes
"Python has only one type of module object, and all modules are of this type, regardless of whether the module is implemented in Python, C, or something else."2 A package is such a module with a __path__. The reference warns against a literal reading of the directory picture: "don’t take this analogy too literally since packages and modules need not originate from the file system."2
References
- The Python Tutorial, 6. Modules, 6.4. Packages
- The Python Language Reference, 5. The import system, 5.2. Packages; 5.2.1. Regular packages; 5.3.1. The module cache; 5.4.2. Submodules
- The Python Language Reference, 3. Data model, 3.2.9.1. Import-related attributes on module objects, module.__path__ and module.__package__
- The Java Language Specification, Java SE 25 Edition, Chapter 7. Packages and Modules, 7.1. Package Members
- The Rust Programming Language, 7.2. Defining Modules to Control Scope and Privacy, Modules Cheat Sheet
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag X9CATP Edit this page History Report an error Markdown