Featureadvanced
Namespace packages
Also called namespace package, implicit namespace package, PEP 420, portion, package without __init__.py, _NamespacePath, NamespacePath, NamespaceLoader, pkgutil.extend_path.
A namespace package is a package without __init__.py. Its __path__ joins directories of the same name from several sys.path entries, so separate distributions can share one parent package.
- Language
- Python
Synopsis
project1/ # one sys.path entry
parent/ # no __init__.py: a portion of the namespace package parent
child/
one.py
project2/ # another sys.path entry
parent/
child/
two.py
import parent.child.one # parent.__path__ lists project1/parent and project2/parent
import parent.child.two # found in the second portion
Semantics
r1. Python has "two types of packages, regular packages and namespace packages."1 "A namespace package is a composite of various portions, where each portion contributes a subpackage to the parent package. Portions may reside in different locations on the file system."1 PEP 420 defines a portion as "a set of files in a single directory (possibly stored in a zip file) that contribute to a namespace package."2 Example: portions.
r2. No file marks a namespace package. "Namespace packages cannot contain an init.py."2 "There will be no marker file or directory for specifying a namespace package."2 The glossary says that namespace packages "allow several individually installable packages to have a common parent package. Otherwise, it is recommended to use a regular package."3
r3. For each directory in the parent path, the import system looks for a name foo in this order. "If /foo/init.py is found, a regular package is imported and returned. If not, but /foo.{py,pyc,so,pyd} is found, a module is imported and returned."2 "If not, but /foo is found and is a directory, it is recorded and the scan continues with the next directory in the parent path."2 "If the scan completes without returning a module or package, and at least one directory was recorded, then a namespace package is created."2 Examples: module-wins, regular-wins.
r4. The namespace package "Has a path attribute set to an iterable of the path strings that were found and recorded during the scan. Does not have a file attribute."2 The reference adds: "Namespace packages do not use an ordinary list for their path attribute. They instead use a custom iterable type which will automatically perform a new search for package portions on the next import attempt within that package if the path of their parent package (or sys.path for a top level package) changes."1 Examples: portions, dynamic.
r5. A namespace package can be nested. "When the import system searches a regular package’s path and encounters a subdirectory that does not contain an init.py file, that subdirectory becomes a portion contributing to a namespace subpackage of the enclosing regular package."1
r6. "Once a namespace package is created, there is no functional difference between it and a regular package."2 PEP 420 lists the differences in how the two are made. Among them: "Namespace packages have no file attribute", "Namespace packages have no init.py module", and "Namespace packages have a different type of object for their loader attribute."2 That loader is importlib.machinery.NamespaceLoader, which "is only made public for introspecting the loader attribute on namespace packages".4 Example: attributes.
Examples
Two directories on sys.path each give a part of parent.child (rules r1 and r4). The __path__ of each namespace package lists both portions.
NAME = "one"
NAME = "two"
import os
import sys
sys.path += ["project1", "project2"]
import parent.child.one
import parent.child.two
print(parent.child.one.NAME, parent.child.two.NAME)
print([os.path.relpath(p) for p in parent.__path__])
print([os.path.relpath(p) for p in parent.child.__path__])
one two
['project1/parent', 'project2/parent']
['project1/parent/child', 'project2/parent/child']
The __path__ of a namespace package follows sys.path (rule r4). A portion added after the first import is found by the next import.
NAME = "one"
NAME = "three"
import os
import sys
sys.path.append("project1")
import parent.child.one
try:
import parent.child.three
except ModuleNotFoundError as e:
print("not found:", e.name)
sys.path.append("project3")
import parent.child.three
print(parent.child.three.NAME)
print([os.path.relpath(p) for p in parent.__path__])
not found: parent.child.three
three
['project1/parent', 'project3/parent']
A namespace package has no __init__.py to run, and its loader is a NamespaceLoader (rule r6). PEP 420 says that it has no __file__. On the CPython versions tested here, the attribute exists and its value is None, and __spec__.origin is also None.
NAME = "one"
import sys
from importlib.machinery import NamespaceLoader
sys.path.append("project1")
import parent
print(parent.__file__)
print(isinstance(parent.__loader__, NamespaceLoader))
print(parent.__spec__.origin)
print("(namespace)" in repr(parent))
None
True
None
True
A directory has the lowest priority (rule r3). The directory tools in project1 is recorded, but the module tools.py in project2 is returned.
NAME = "helpers"
NAME = "tools.py"
import os
import sys
sys.path += ["project1", "project2"]
import tools
print(tools.NAME)
print(os.path.relpath(tools.__file__))
tools.py
project2/tools.py
Versions
The type of a namespace __path__ is a private class _NamespacePath on CPython 3.12.3, 3.13.14 and 3.14.6. On CPython 3.15.0b2 the class is NamespacePath. The 3.15 importlib page lists importlib.machinery.NamespacePath, which "Represents a namespace package’s path (module.path)", and the page marks it as a 3.15 addition.4 The examples on this page do not print the type, and they give the same output on the four versions.
Pitfalls
One __init__.py stops the scan
A regular package returns at once (rule r3). If one portion has an __init__.py, the import system does not look at the other directories, and their subpackages are not found.
"""This file makes project1/parent a regular package."""
NAME = "one"
NAME = "two"
This code raises ModuleNotFoundError, on purpose.
import sys
sys.path += ["project1", "project2"]
import parent.child.one
import parent.child.two
All the portions of a namespace package must leave out __init__.py.
Any directory can be imported
Because no marker file is needed (rule r2), import accepts a directory that is not code. Here config/ holds only a data file. The import succeeds, and the error comes later.
debug = true
This code raises AttributeError, on purpose.
import config
print(config.__file__)
config.load()
The tutorial gives the reason that regular packages need __init__.py: "This prevents directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path."5 A namespace package does not hide a module (rule r3), but a mistyped or missing module name can still import an unrelated directory.
Code in __init__.py of a portion
PEP 420 explains the old way, pkgutil.extend_path, and its problem: "the package’s init.py cannot practically define any names as it depends on the order of the package fragments on sys.path to determine which portion is imported first."2 A namespace package has no place for shared code at the top. Put shared code in a subpackage that one distribution owns.
Comparison
Go ties a package to its source files: "A set of files sharing the same PackageName form the implementation of a package. An implementation may require that all source files for a package inhabit the same directory."6 Python can build one package from directories on different sys.path entries.
Java modules take the opposite rule for a package. A package is uniquely visible to a module M when no compilation unit of M declares it "and M reads exactly one other module that exports the package to M."7 So a package that two modules export to M is not uniquely visible to M. Two portions of one Python namespace package are the normal case.
Implementation notes
PEP 420 gives the reason for the dynamic __path__: "this PEP requires that the list of path entries be dynamically computed when each portion is loaded. It is expected that the import machinery will do this efficiently by caching path values and only refreshing them when it detects that the parent path has changed."2 It also explains why __init__.py was dropped: Linux vendors install portions "into the same file system directory. This creates a potential for conflict, as the portions are now attempting to provide the same file on the target system".2
References
- The Python Language Reference, 5. The import system, 5.2. Packages; 5.2.1. Regular packages; 5.2.2. Namespace packages
- PEP 420: Implicit Namespace Packages, Abstract; Rationale; Specification; Dynamic path computation; Differences between namespace packages and regular packages; Packaging Implications
- Glossary, Python 3.15 documentation, namespace package
- importlib — The implementation of import, importlib.machinery.NamespaceLoader; importlib.machinery.NamespacePath
- The Python Tutorial, 6. Modules, 6.4. Packages
- The Go Programming Language Specification, Packages
- The Java Language Specification, Java SE 25 Edition, Chapter 7. Packages and Modules, 7.4.3. Package Observability and Visibility
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 Q9RVY4 Edit this page History Report an error Markdown