How to create python namespace packages in Python 3?


Using namespace packages, you can distribute the sub-packages and modules of one package among many, independent distribution packages (referred to as distributions in this document to avoid ambiguity).

In Python, a namespace package allows you to spread Python code among several projects. This is useful when you want to release related libraries as separate downloads.

Creating a namespace package

Currently, there are three methods for developing namespace packages. These methods are mentioned below.

  • Use packages for native namespaces. The PEP 420 specification for this kind of namespace package states that Python 3.3 and later support it. If packages in your namespace only ever need to support Python 3 and pip installation, then doing so is advised.

  • Use namespace packages in the pkgutil style. For new packages that require support for Python 2 and 3 and installation via both pip and python setup.py install, this is advised.

  • Use namespace packages in the pkg resources manner. This approach is suggested if your package needs to be zip-safe or if you need it to work with other packages that already use it.

Example 1

For example, with the directories Package-1 and Package-2 in PYTHONPATH, the end-user can import namespace.module1 and import namespace.module2. The code below shows the namespaces in each package.

Package-1/namespace/__init__.py Package-1/namespace/module1/__init__.py Package-2/namespace/__init__.py Package-2/namespace/module2/__init__.py

Example 2

This example can be used to understand how to namespaces are present when sub packages are a part of packages in python.

mynamespace/ __init__.py subpackage_a/ __init__.py ... subpackage_b/ __init__.py ... module_b.py Setup.p

Packages for native namespaces

Implicit namespace packages from PEP 420 were added to Python 3.3. You only need to remove __init .py from the directory containing the namespace package in order to establish a native namespace package. a model of a file structure

setup.py mynamespace/ # No __init__.py here. subpackage_a/ # Sub-packages have __init__.py. __init__.py module.py

Namespace packages in the pkgutil style

Example 

The pkgutil module and pkgutil.extend path() function were first made available in Python 2.3. This can be used to declare namespace packages that must work with Python 2.3 and later as well as Python 3. The best course of action for the highest level of compatibility is this one. You must include a __init .py file for the namespace package in order to construct a namespace package in the pkgutil style −

setup.py mynamespace/ __init__.py # Namespace package __init__.py subpackage_a/ __init__.py # Sub-package __init__.py module.py

Updated on: 16-Sep-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements