Namespace packages with a core part?

╄→尐↘猪︶ㄣ 提交于 2019-12-05 02:43:01

It is indeed not possible to have code in a top level __init__.py for a PEP 420 namespace package.

If I were you, I'd either:

  1. create 2 packages, one called mylibrary (a normal package) which contains your actual library code, and the other called mylibrary_plugins which is a namespace package.
  2. or, create mylibrary.lib, which is a normal package and contains your code, and mylibrary.plugins, which is a namespace package.

Personally I'd use option 1.

The rationale section of PEP 420 explains why __init__.py cannot contain any code.

strictly speaking, you can have variables under mylibrary, you just won't be able to define them there. You can, for instance:

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

mylibrary.some_function = some_function

and your users can use it like:

import mylibrary.core
mylibrary.some_function()

That is to say, mylibrary.core monkey patches mylibrary so that, other than the import, it looks as though somefunction is defined in mylibrary rather than a sub-package.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!