简体   繁体   English

如何在 Python 中创建命名空间包?

[英]How to create namespace packages in Python?

I have a Python 3 project with the following structure:我有一个 Python 3 项目,其结构如下:

project/
|
+--root/
   |
   +--__init__.py
   |
   +--sub/
      |
      +--__init__.py
      |
      +--actualcode.py

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

The __init__.py file in the root folder contains the following statement to create a namespace package:根文件夹中的__init__.py文件包含以下用于创建命名空间 package 的语句:

from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)

But I cannot reference the code when I import root.sub .但是当我导入root.sub时我无法引用代码。 It works only when I write:它仅在我编写时才有效:

from sub.actualcode import something # doesn't work with "root.sub..."!

What should I do to use root as a namespace?我应该怎么做才能使用root作为命名空间?

Namespace packages can be built with distribute .命名空间包可以使用 分发构建。 The trick is then to add the following line to the parameter of setup :诀窍是将以下行添加到setup的参数中:

setup(
  # ...
  namespace_packages  = ["root"]
)

The rest of the example in the question is correct.问题中示例的 rest 是正确的。

I just tried your example, but it seems to work like you want it to:我刚刚尝试了您的示例,但它似乎像您希望的那样工作:

    >>> from root.sub.actualcode import foo
    >>> foo()
    Bar!

I ran the Python interpreter from the directory containing the root folder.我从包含root文件夹的目录中运行了 Python 解释器。 I created the empty __init__.py files and my actualcode.py looks like this:我创建了空的__init__.py文件,我的actualcode.py看起来像这样:

    #!/bin/python3

    def foo():
        print("Bar!")

The difference is that my __init__.py files are empty.不同之处在于我的__init__.py文件是空的。

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

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