10

This question follows up The way to make namespace packages in Python and How do I create a namespace package in Python?.

Note PEP 420, and the distribute docs, which state:

You must NOT include any other code and data in a namespace package’s __init__.py. Even though it may appear to work during development, or when projects are installed as .egg files, it will not work when the projects are installed using “system” packaging tools – in such cases the __init__.py files will not be installed, let alone executed.


This all seems to make it impossible to have a "main library" package with independently distributed extension sub-packages. What I want is to be able to:

  1. define a core library package, to be used like this:

    import mylibrary
    
    mylibrary.some_function()
    
  2. allow library extensions, packaged and distributed separately, to be used like this:

    import mylibrary.myextension
    
    mylibrary.myextension.some_other_function()
    

I would've expected to be able to do this with namespace packages, but it seems not to be the case, based on the questions and links above. Can this be done at all?

4

2 回答 2

4

__init__.py在PEP 420 命名空间包的顶层中确实不可能有代码。

如果我是你,我会:

  1. 创建 2 个包,一个名为 mylibrary (一个普通包),其中包含您的实际库代码,另一个名为 mylibrary_plugins ,它是一个命名空间包。
  2. 或者,创建 mylibrary.lib,它是一个普通包并包含您的代码,以及 mylibrary.plugins,它是一个命名空间包。

我个人会使用选项1。

PEP 420 的基本原理部分解释了为什么__init__.py不能包含任何代码。

于 2013-01-21T15:37:54.303 回答
1

严格来说,你可以在 下变量mylibrary,你只是不能在那里定义它们。例如,您可以:

# mylibrary/core.py
import mylibrary
def some_function():
    pass

mylibrary.some_function = some_function

您的用户可以像这样使用它:

import mylibrary.core
mylibrary.some_function()

也就是说,mylibrary.coremonkey 补丁mylibrary使得除了导入之外,它看起来好像somefunction是在mylibrary而不是子包中定义的。

于 2013-08-01T11:01:05.463 回答