namespace package

In Python, a namespace package is a type of package that allows you to split a single package across multiple directories.

Namespace packages are particularly useful when you want to distribute different parts of a package separately, or when you want to combine modules from different sources under a common namespace.

Unlike regular packages, namespace packages do not require an __init__.py file, which makes them more flexible and manageable when dealing with large codebases or third-party libraries.

Namespace packages enable you to organize your code in a modular way, making it easier to scale and maintain. With namespace packages, you can have multiple directories on your sys.path that contribute to the same package, and Python will seamlessly combine them at runtime.

Example

Suppose you have a project structure like this:

project_a/
└── namespace/
    └── module_a.py

project_b/
└── namespace/
    └── module_b.py

Assuming the parent directories have been added to sys.path, both project_a and project_b contribute to the same namespace package without requiring an __init__.py file in the namespace/ directories. You can import modules from both projects like this:

Python
# Importing module_a from project_a
from mynamespace import module_a

# Importing module_b from project_b
from namespace import module_b

This allows you to work with a unified namespace, where module_a and module_b coexist under namespace.

Tutorial

What's a Python Namespace Package, and What's It For?

In this tutorial, you'll be exploring Python namespace packages: what they are, what they're for, and how you can use them in your package systems. Along the way, you'll create your own set of namespace packages and explore how you might be able to use them in your own projects.

advanced python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 17, 2025 • Reviewed by Dan Bader