packaging common python namespaces

2019-01-31 14:46发布

问题:

I'm looking to package and upload a library I have to PyPI in the next few days, but I'm a little unsure about my approach to the namespace.

I have a few otherwise unrelated projects with a similar approach and wanted to give them all the same namespace. For example:

  • Library 1 namespace: abc.seo
  • Library 2 namespace: abc.ajax
  • Library 3 namespace: abc.ecommerce
  • etc

The problem is that I'm not sure if it's possible for two separate packages (eg eggs) to co-exist with the same parent namespace. Is this approach problematic, or is there a way around it? What's the best approach?

The libraries should not be packaged together, they are too unrelated. I would like to get it right before uploading so as to avoid painful namespace changes after making an "official" release.

(NB abc is not the real name, I wanted my question to be free from advertising)

UPDATE

I went with the following, to be nice to the people without setuptools installed:

try:
    __import__('pkg_resources').declare_namespace(__name__)
except ImportError:
    __path__ = __import__('pkgutil').extend_path(__path__, __name__)

With the following in setup.py:

setup(
    ...
    namespace_packages = ['rollyourown'],
    ...

回答1:

In each project base directory, create the following structure:

/setup.py
/abc/__init__.py
/abc/seo/

/abc/__init__.py contains :

__import__('pkg_resources').declare_namespace(__name__)

setup.py contains :

setup(...,
    packages: ['abc', 'abc.seo'],
    namespace_packages = ['abc']
    ...
)

Reference documentation: namespace packages.