开发者

How to create namespace packages in Python?

I have a Python 3 project with the following structure:

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:

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

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..."!

What should I do to use root as a namespace?


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.


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. I created the empty __init__.py files and my actualcode.py looks like this:

    #!/bin/python3

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

The difference is that my __init__.py files are empty.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜