Namespace packages in Python enable the distribution of related libraries as individual downloads. This article explains how to define namespace packages to allow multiple Python products to share a common namespace.
Implicit Namespace Packages
Starting from Python 3.3, implicit namespace packages are available. These packages are directories without __init__.py files, and they are searched for when no module is found in the current path. Modules and packages can be imported under implicit namespace packages using dot notation.
Mixing Regular and Namespace Packages
To allow interoperability between regular packages (with __init__.py files) and namespace packages, the pkgutil.extend_path() method has been extended. Regular packages that declare namespace extensions will add both regular and namespace packages to their __path__.
Example Directory Structure
Consider the following directory structure:
├── path1 │ └── package │ ├── __init__.py │ └── foo.py ├── path2 │ └── package │ └── bar.py └── path3 └── package ├── __init__.py └── baz.py
With the appropriate pkgutil.extend_path() declarations, the following imports will be successful:
pkg_resources.declare_namespace()
The pkg_resources.declare_namespace() method has not been updated to support implicit namespace packages.
Conclusion
Defining namespace packages allows for modularity and flexibility in Python package development. By leveraging implicit namespace packages and the extended pkgutil.extend_path() solution, developers can create namespace packages that can be shared and used by multiple products.
The above is the detailed content of How Do I Define Namespace Packages for Multiple Python Products?. For more information, please follow other related articles on the PHP Chinese website!