如何在Python中创建名称空间包? [英] How to create namespace packages in Python?
问题描述
我有一个具有以下结构的Python 3项目:
I have a Python 3 project with the following structure:
project/
|
+--root/
|
+--__init__.py
|
+--sub/
|
+--__init__.py
|
+--actualcode.py
我想使用命名空间包",以便我的库与单独项目中的其他相关库共享一个公共名称空间. import语句应如下所示:
I want to use "namespace packages" so that my lib shares a common namespace with other related libs in separate projects. The import statement should look like this:
from root.sub.actualcode import something
根文件夹中的__init__.py
文件包含以下用于创建名称空间包的语句:
The __init__.py
file in the root folder contains the following statement to create a namespace package:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
但是导入root.sub
时我无法引用代码.它仅在我写时起作用:
But I cannot reference the code when I import root.sub
. It works only when I write:
from sub.actualcode import something # doesn't work with "root.sub..."!
如何使用root
作为命名空间?
What should I do to use root
as a namespace?
推荐答案
可以使用分发.然后,诀窍是将以下行添加到setup
的参数中:
Namespace packages can be built with distribute. The trick is then to add the following line to the parameter of setup
:
setup(
# ...
namespace_packages = ["root"]
)
问题中其余示例都是正确的.
The rest of the example in the question is correct.
这篇关于如何在Python中创建名称空间包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!