Sub topic 16
Namespace packages without __init__.py
This chapter assumes you can create regular packages with __init__.py, that you know how sys.path is searched, and that you understand how sys.modules caches imports. Here you will learn how a directory with no __init__.py can still be imported, what Python builds in that case, and when the feature is useful or risky.
What a namespace package is
A regular package is a directory with an __init__.py file. A namespace package is a package with no __init__.py, and it can be spread across several directories. Each directory contributes a portion of the package. Python merges the portions into a single package object.
The usual reason to use one is to let separately installed distributions share a top-level name. For example, acme-billing and acme-reports can each install modules under acme/ without either one owning the acme package. Both can be installed in any order, and import acme.billing and import acme.reports both work.
A runnable example
This script builds two separate directories, each holding a portion of acme. It then puts both on sys.path.
import sys
import tempfile
from pathlib import Path
root = Path(tempfile.mkdtemp())
portions = [
("dist_a", "billing", "NAME = 'billing'"),
("dist_b", "reports", "NAME = 'reports'"),
]
for dist, module, source in portions:
pkg_dir = root / dist / "acme"
pkg_dir.mkdir(parents=True)
(pkg_dir / f"{module}.py").write_text(source + "\n")
sys.path.append(str(root / dist))
import acme.billing
import acme.reports
print([Path(p).relative_to(root) for p in acme.__path__])
print(getattr(acme, "__file__", None))
print(acme.billing.NAME, acme.reports.NAME)The output shows acme.__path__ holding two entries, dist_a/acme and dist_b/acme. __file__ is None (or absent), because no single file defines the package. Both submodules import normally.
How Python finds a namespace package
The path-based finder checks each sys.path entry in order. For each entry it looks for a name in this order:
- A directory named
acmecontaining__init__.py. This is a regular package. The search stops and this package is used. - A file such as
acme.py, or a compiled extension. This is a module. The search stops. - A directory named
acmewith no__init__.py. The finder records it as a possible portion and keeps searching.
If the search reaches the end of sys.path without finding a regular package or module, Python creates a namespace package from the recorded portions.
The order of the checks matters. A regular package found later on sys.path beats directories found earlier, because the regular package ends the search.
What the package object looks like
A namespace package is still a module object, but several attributes differ from a regular package.
| Attribute | Regular package | Namespace package |
|---|---|---|
| `__init__.py` | Required | None |
| `__file__` | Path to `__init__.py` | `None` or absent |
| `__path__` | List of one directory | Dynamic path over all portions |
| `__spec__.origin` | Path to `__init__.py` | `None` |
| Code that runs on import | The contents of `__init__.py` | Nothing |
| Can define `__all__` or re-export names | Yes | No |
The __path__ of a namespace package is recomputed. If sys.path changes after the first import, for example because you append a directory that holds a third portion, Python picks up the new portion the next time it searches acme.__path__. You do not need to reload anything. The cached acme object in sys.modules stays the same.
Namespace packages in a project
Two common layouts use this feature.
The first is a shared prefix across distributions:
acme-billing/
pyproject.toml
src/
acme/
billing/
__init__.py
invoices.py
acme-reports/
pyproject.toml
src/
acme/
reports/
__init__.py
summary.pyNote that acme/ has no __init__.py, while billing/ and reports/ are regular packages. This is the intended pattern. The shared top level is a namespace, and each distribution owns one regular subpackage under it. Neither distribution may install a file at acme/__init__.py. If one did, it would turn acme into a regular package and hide the other portion.
The second is a missing __init__.py on purpose or by accident, in a single project. Python 3.3 and later import such a directory without complaint, so an omitted __init__.py no longer raises an error.
For packaging, setuptools includes namespace packages when you ask for them explicitly. A pyproject.toml for one distribution could say:
[tool.setuptools.packages.find]
where = ["src"]
include = ["acme.*"]
namespaces = trueWithout namespaces = true, automatic package discovery skips directories that have no __init__.py, and your modules would be missing from the built wheel.
Gotchas and common errors
- A directory becomes importable by accident. Any directory on
sys.pathnamed like your import can be a namespace portion. A folder calledutils/ortest/in your working directory is enough. This is the shadowing pitfall from earlier chapters, in a new form. - A stray file blocks the namespace. If one portion adds
acme/__init__.py, the finder stops at it and the other portions become unreachable. The error shows up asModuleNotFoundError: No module named 'acme.reports', even though the files exist. - Import order seems not to matter, but search order does. If two portions both contain
acme/utils.py, the portion that appears first inacme.__path__wins. Overlapping module names between portions are a bug, so avoid them. - Tools that expect
__init__.py. Some test runners, type checkers, and documentation generators treat directories without__init__.pydifferently. Check their namespace-package settings if modules are not found. - Old declaration styles. Before Python 3.3, shared names were declared with
pkgutil.extend_pathorpkg_resources.declare_namespaceinside__init__.py. Those are still seen in older code. They makeacmea regular package, so do not mix them with the implicit style for the same name.
Inspecting a namespace package
You can check what Python found without reading the filesystem yourself.
import importlib.util
spec = importlib.util.find_spec("acme")
print(spec.origin)
print(spec.submodule_search_locations)
print(spec.loader)For a namespace package, spec.origin is None, and submodule_search_locations lists the portions. This is the quickest way to find out why an import resolves to the wrong place. Run it in the same environment as the failing code, because sys.path decides the answer.
Deciding whether to use one
Use a namespace package when several independently released distributions must share a top-level name and none of them should own it. Use a regular package in all other cases. A regular package is easier for tools to find, gives you a place for a public interface, and cannot be hidden by a stray directory.
Exercise
A project has libs/acme/core.py and plugins/acme/__init__.py with plugins/acme/extra.py. Both libs and plugins are on sys.path, with libs first. What does import acme.core do, and why?
Show answer
It raises ModuleNotFoundError. The finder sees libs/acme first and records it as a namespace portion, since it has no __init__.py. It then finds plugins/acme/__init__.py, a regular package, and stops there. The regular package wins, so acme refers only to plugins/acme, which has no core module. Fix it by removing plugins/acme/__init__.py so both are portions, or by moving the modules into one package.