Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Name spacing your modules in Python

Tags:

python

I have several repos that I want to name space. All of the repos follow the standard Python folder structures where

repo1 - repo1 - __init__.py

Outermost repo1 folder is the root folder and the inner repo1 folder is the root of the module. All of these repos will be installed using

pip install -e .

Currently, import statements like the following is used to import these modules.

import repo1
import repo2
import repo3

Is there a way to name space these modules so that I can have

import mymodule.repo1
import mymodule.repo2
import mymodule.repo3

I have to achieve the name spacing while keeping the repos separate. Merging the repos is not an option at this moment.

like image 842
jiminssy Avatar asked May 29 '26 05:05

jiminssy


1 Answers

Implementation details depends on your needs for version support and distribution, but take a look at setuptools namespace_packages, this will do the work.

As pointed above, packaging site has an useful page on namespaced packaging.


Example for native namespaces (python >=3.3). Project layout for isolated repos:

project_root1
├── finance_namespace  # no __init__ file here, this is important
│   └── repo1
│       ├── __init__.py  
│       └── module1.py
└── setup.py

===============================

# setup.py
import setuptools

setuptools.setup(
    name='repo1',
    version='1',
    description='',
    long_description='',
    author='Big bank',
    author_email='[email protected]',
    license='MIT',
    packages=['finance_namespace.repo1'],
    zip_safe=False,
)

Now, by making cd project_root1 && pip install -e . you should be able to do

>>> from finance_namespace.repo1 import module1
>>> module1.func()
like image 113
Slam Avatar answered May 30 '26 18:05

Slam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!