简体   繁体   English

如何为setuptools发布创建嵌套命名空间包

[英]How to create nested namespace packages for setuptools distribution

I'm developing a python project that will have separately distributable parts. 我正在开发一个python项目,它将具有可单独分发的部分。

I have been able to accomplish part of my goal by making a namespace package . 通过创建命名空间包 ,我已经能够完成部分目标。 I have "sub1" and "sub2", both in namespace "lvl1". 我在命名空间“lvl1”中都有“sub1”和“sub2”。 I can pip install these in development mode using "pip install -e" or python setup.py develop . 我可以使用“pip install -e”或python setup.py develop在开发模式下安装这些。 I can import them with import lvl1.sub1 and import lvl1.sub2 . 我可以使用import lvl1.sub1导入它们并import lvl1.sub2

However, the project is massive and calls for nested namespaces . 但是,该项目规模庞大,需要嵌套命名空间 I want to import lvl1.lvl2.sub1 and import lvl1.lvl2.sub2 . 我想import lvl1.lvl2.sub1import lvl1.lvl2.sub2 So both subpackages are in the same namespace ("lvl2"), which is itself in a namespace ("lvl1"). 因此,两个子包都位于相同的命名空间(“lvl2”)中,它本身位于命名空间(“lvl1”)中。

Desired conceptual structure: 理想的概念结构:

lvl1/
    lvl2/
        sub1/
            code.py
            more_code.py
            ...
        sub2/
            code.py
            ...

Is there a way to do this and how? 有办法做到这一点,怎么做?

Yes there is more than one way. 是的,不止一种方式。 Please read section "Nested namespace packages" in PEP 420 . 请阅读PEP 420中的“嵌套命名空间包”部分

In python >= 3.3, the easiest way to make nested namespace is to delete (do not include) file __init__.py in the specific folders ("lvl1" and "lvl2") in every distributable parts. 在python> = 3.3中,制作嵌套命名空间的最简单方法是在每个可分发部分中的特定文件夹(“lvl1”和“lvl2”)中删除(不包括)文件__init__.py In each of the setup.py , explicitly list all the packages in the deepest namespace. 在每个setup.py ,显式列出最深的命名空间中的所有包。

"lvl1_part1/setup.py" “lvl1_part1 / setup.py”

setup(
    name='lvl1_part1',
    ...
    zip_safe=False,
    packages=['lvl1.lvl2.sub1']
)

"lvl1_part2/setup.py" “lvl1_part2 / setup.py”

setup(
    name='lvl1_part2',
    ...
    zip_safe=False,
    packages=['lvl1.lvl2.sub2']
)

The file structure for testing: 用于测试的文件结构:

lvl1_part1/
           setup.py
           lvl1/
                lvl2/
                     sub1/
                          __init__.py
lvl1_part2/
           setup.py
           lvl1/
                lvl2/
                     sub2/
                          __init__.py

To make the above packages compatible to older python versions, please add the pkgutil magic file to each of the "lvl1" and "lvl2" folders. 要使上述软件包与旧的python版本兼容,请将pkgutil magic文件添加到每个“lvl1”和“lvl2”文件夹中。

Credits: The example above is modified from https://github.com/pypa/sample-namespace-packages/tree/master/pkgutil 致谢:上面的例子是从https://github.com/pypa/sample-namespace-packages/tree/master/pkgutil修改的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM