Python namespace packages
last modified November 29, 2026 Python 3.15
In this article we look at namespace packages, a feature defined by PEP 420 and
available since Python 3.3. A namespace package is a package without an
__init__.py file. Python can merge several directories with the
same name into one importable package, which lets separate distributions share
a common namespace.
Regular packages and their __init__.py file are covered in
Python __init__.py file, and packages in
general in Python package.
A directory without __init__.py
A directory without __init__.py is still a package. Python creates
a namespace package for it when the directory is found on the module search
path. The package object has no file and no initialization code, but it has a
__path__ that lists the directories the name was found in.
.
├── main.py
└── tools/
└── convert.py
The tools directory contains a module and no
__init__.py. The program prints the package attributes and calls
the function from the submodule.
def to_upper(text):
return text.upper()
__file__ is None because no file represents the
package, and __spec__.origin is None for the same
reason. The type of __path__ is NamespacePath in
Python 3.15; older versions used _NamespacePath.
import os
import tools
from tools import convert
print(tools.__file__)
print(tools.__spec__.origin)
print(type(tools.__path__).__name__)
print([os.path.relpath(p) for p in tools.__path__])
print(convert.to_upper('python'))
There is one directory in the path, and the submodule is imported normally
despite the missing __init__.py. Note that
tools.__doc__ is None and the package cannot hold a
version string, because there is no file to put them in.
$ python main.py None None NamespacePath ['tools'] PYTHON
Joining portions from two directories
The useful case begins when the same package name appears in more than one place. Each matching directory is called a portion of the namespace package, and Python combines all portions it finds on the search path into a single package object.
.
├── main.py
├── dir1/
│ └── tools/
│ └── logutils.py
└── dir2/
└── tools/
└── formatting.py
Neither dir1/tools nor dir2/tools has an
__init__.py. One portion provides a logging helper and the other a
text formatter.
def log_message(message):
print(f'[LOG] {message}')
The formatter in the second portion has its own module name, so the two directories do not collide.
def to_title(text):
return text.title()
The program puts both directories on sys.path before importing.
The slice sys.path[1:1] inserts them right after the script's own
directory. This works when the program is run from the project directory; an
application normally gets the same effect from its installation layout or the
PYTHONPATH variable.
import os
import sys
sys.path[1:1] = ['dir1', 'dir2']
import tools
from tools import formatting, logutils
print([os.path.relpath(p) for p in tools.__path__])
print(os.path.relpath(formatting.__file__))
print(os.path.relpath(logutils.__file__))
logutils.log_message('starting')
print(formatting.to_title('hello world'))
The package path now has two entries, and each module reports the portion it was loaded from. The two functions behave as if they lived in one package, which is exactly how a plugin system or a set of separately installed distributions uses a namespace package.
$ python main.py ['dir1/tools', 'dir2/tools'] dir2/tools/formatting.py dir1/tools/logutils.py [LOG] starting Hello World
A regular package wins over namespace portions
The merge happens only while no regular package or module with the same name is
found. A directory with __init__.py is a regular package, and a
regular package found anywhere on the search path wins over namespace portions,
even ones that come earlier. This is the most common surprise when a project
gradually adds an __init__.py.
.
├── main.py
├── dir1/
│ └── tools/
│ ├── __init__.py
│ └── local.py
└── dir2/
└── tools/
└── remote.py
dir1/tools is now a regular package, while
dir2/tools is still a namespace portion. The
__init__.py may be empty or contain a docstring.
"""Local tools package."""
Each portion still has a module of its own. The program imports the package and tries to import the module from the second directory.
def ping():
return 'local'
dir2/tools/remote.py is identical apart from the returned string,
but it is never reached: the regular package stops the search at its own
directory.
def ping():
return 'remote'
The program catches the failed import so that the error is visible without a
traceback. The package path has one entry and the package has a real
__file__.
import os
import sys
sys.path[1:1] = ['dir1', 'dir2']
import tools
print(os.path.relpath(tools.__file__))
print([os.path.relpath(p) for p in tools.__path__])
try:
import tools.remote
except ModuleNotFoundError as e:
print(type(e).__name__ + ':', e)
The error message names the missing submodule, not a problem with the path.
The order of dir1 and dir2 does not change the
outcome: a regular package is preferred over namespace portions wherever it
appears. Two regular packages with the same name behave differently, and there
the first one on sys.path is used.
$ python main.py dir1/tools/__init__.py ['dir1/tools'] ModuleNotFoundError: No module named 'tools.remote'
Relative imports between portions
A namespace package has no __init__.py, but it is still a package
object, so relative imports work inside its modules. A module in one portion
can import a sibling from another portion with the usual dot notation.
.
├── main.py
├── dir1/
│ └── tools/
│ └── convert.py
└── dir2/
└── tools/
└── report.py
The first portion holds the conversion function, and the second builds a report
from it. The relative import in report.py does not mention
dir1 or dir2; it only names the package.
def to_upper(text):
return text.upper()
from . import convert asks the tools package for its
convert submodule. Python searches all portions in
tools.__path__ and finds the module in the first one.
from . import convert
def report(text):
return convert.to_upper(text) + '!'
The program imports the reporting module and prints the file behind the imported submodule, which shows that the two portions really were combined. See Python relative imports for the full syntax.
import os
import sys
sys.path[1:1] = ['dir1', 'dir2']
from tools import report
print(report.report('hello'))
print(os.path.relpath(report.convert.__file__))
The call crosses the directory boundary without any path handling in the
module, and the printed path confirms that convert came from
dir1.
$ python main.py HELLO! dir1/tools/convert.py
Namespace package and regular package compared
The same directory name behaves differently depending on one file. A namespace
package has no __file__, no docstring, and a dynamic path; a
regular package has all three. This example places both forms side by side.
.
├── main.py
├── nspkg/
│ └── info.py
└── regpkg/
├── __init__.py
└── info.py
The two packages contain a module with the same function. Only
regpkg has an __init__.py, and that file carries a
docstring.
def describe():
return 'namespace portion'
The regular package's module returns a different string, so the origin of each result is clear.
"""Regular package."""
The program prints the name, the type of __path__, and the
docstring for both packages.
def describe():
return 'regular package'
The difference in the path type is the clearest signal: a list belongs to a
regular package, while a namespace package exposes a NamespacePath
that can be recomputed when sys.path changes.
import nspkg
import regpkg
for pkg in (nspkg, regpkg):
print(pkg.__name__, type(pkg.__path__).__name__, pkg.__doc__)
The regular package reports its docstring; the namespace package reports
None, because no file could define one. Neither package's modules
are imported here, which is why their describe functions do not
appear in the output.
$ python main.py nspkg NamespacePath None regpkg list Regular package.
Discovering modules across portions
The __path__ of a namespace package is a real search path, so tools
that scan directories work with it. A plugin loader can walk every portion and
import each module it finds, and a new distribution that installs another
module into the namespace becomes visible without changes to the loader.
.
├── main.py
├── dir1/
│ └── tools/
│ └── logutils.py
└── dir2/
└── tools/
└── formatting.py
The two modules are the ones from the earlier example.
pkgutil.iter_modules accepts a path list and yields one record per
module, and importlib.import_module loads it by its full name.
import importlib
import pkgutil
import sys
sys.path[1:1] = ['dir1', 'dir2']
import tools
for info in pkgutil.iter_modules(tools.__path__):
module = importlib.import_module(f'tools.{info.name}')
print(info.name, '->', module.__name__)
Both modules are found even though they live in different directories. The
order follows the order of the portions, which follows sys.path,
so a plugin system should not rely on it for anything beyond discovery.
$ python main.py logutils -> tools.logutils formatting -> tools.formatting
Pitfalls and tooling
Namespace packages are convenient, but they remove the file that normally holds package-level information. The following points cover the practical consequences.
- There is no place for initialization code, a docstring, or
__version__. Read the version from the installed distribution withimportlib.metadata.versioninstead. __file__isNone, so code that builds data paths from the package's own file must handle that case or useimportlib.resources.- Adding an
__init__.pyto any portion turns the package regular and hides all other portions. Do not mix the two forms by accident. - Build backends must be told to include directories without
__init__.py; setuptools usesfind_namespace_packagesornamespaces = truein its configuration. - Type checkers, linters, and older packaging tools may need explicit configuration before they resolve a namespace package.
- Uninstalling one distribution removes only its own portion; the others stay.
- The older
pkgutil.extend_pathandpkg_resources.declare_namespacetechniques keep a package regular while splitting it. They are shown in Python __init__.py file and are not needed for new namespace packages.
Source
PEP 420 – Implicit Namespace Packages
Namespace packages – The import system
pkgutil – Package extension utility
Package discovery – setuptools documentation
In this article we have seen how Python merges directories without
__init__.py into namespace packages, how a regular package hides
those portions, and how relative imports and plugin discovery work across
them. See also Python __init__.py file,
Python package,
Python relative imports, and
Python module.
Author
List all Python tutorials.