Sub topic 16
Namespace packages without __init__.py
This chapter assumes you know regular packages with __init__.py, how sys.path is searched, and how absolute imports work.
What a namespace package is
A regular package is one directory with an __init__.py file. A namespace package is a package with no __init__.py. It can also be spread across several directories on sys.path. Python merges those directories into one package.
This lets separate distributions share a top-level name. For example, two teams can ship acme.billing and acme.reports as separate installs. Both end up under one acme package.
How Python finds one
While searching sys.path, the import system checks each entry in order for a given name:
- If it finds
name/__init__.py, it creates a regular package and stops. - If it finds
name.pyor another module file, it imports that module and stops. - If it finds a directory
name/with no__init__.py, it remembers the directory and keeps searching. - If the search ends and it remembered at least one directory, it builds a namespace package from all of them.
A regular package or module found later on the path still wins over directories remembered earlier. Directories only combine when nothing else matches the name.
A worked example
Create two separate directories, each holding part of acme:
site_a/
acme/
billing.py
site_b/
acme/
reports.pyPut one function in each file, then import both through the shared name:
import sys
sys.path.extend(["site_a", "site_b"])
from acme import billing, reports
import acme
print(acme.__path__)
print(acme.__file__)Run this from the directory that contains site_a and site_b. acme.__path__ lists both acme directories. acme.__file__ is None, because a namespace package has no single file. Its __path__ is a special iterable that rechecks sys.path if the path changes, so portions added later are picked up.
Gotchas
- A namespace package cannot run initialization code, because it has no
__init__.py. You cannot define__all__or re-export names at the package level. - If any portion of the shared name contains an
__init__.py, and it is found first, it becomes a regular package. The other portions are then ignored. Shared names need every portion to omit the file. - A stray directory can accidentally become a namespace package. Running
import testsmay succeed in the wrong place, hiding a missing install. - Tools that walk the filesystem may skip directories without
__init__.py. Test discovery in some configurations is one example.
Exercise
You have a/pkg/x.py and b/pkg/__init__.py. Both a and b are on sys.path, with a first. What does import pkg produce, and can you import pkg.x?
Show answer
a/pkg has no __init__.py, so Python records it and keeps searching. It then finds b/pkg/__init__.py and creates a regular package from b/pkg alone. The recorded directory is discarded, so import pkg.x fails with ModuleNotFoundError.