目前我们有一个 Python 库,看起来像这样:
Jupiter/
__init__.py
Ganymede.py
Callisto.py
Ganymede.py 依次包含函数 Foo()、Bar() 等。我们现有的脚本通过
from Jupiter import Ganymede
# later in the program...
Ganymede.Foo()
我想重新组织一下,使目录看起来更像
Jupiter/
__init__.py
Ganymede/
__init__.py
functions.py
Callisto/
__init__.py
functions.py
不破坏或修改任何使用 Jupiter 的现有脚本。
如果 Ganymede/__init__.py 使用 "The import system" documentation 中描述的导入语法:
from .functions import *
然后 Foo() 和 Bar() 最终出现在 Ganymede 的命名空间中,但是 Ganymede 的 help() 没有提到它们.
>>> from Jupiter import Ganymede
>>> dir(Ganymede)
['Bar', 'Foo', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'functions']
>>> help(Ganymede)
Help on package Jupiter.Ganymede in Jupiter:
NAME
Jupiter.Ganymede
PACKAGE CONTENTS
functions
FILE
x:\yadda\yadda\ganymede\__init__.py
我真的非常喜欢 help(Ganymede) 自动列出所有可用的函数和类。
我想我可以从 Ganymede/__init__.py 中 execfile("functions.py") 但我觉得必须有一些更简洁的方法来做到这一点。还是没有?
我需要在 Python 2.7.15 和 3.5.3 中都能工作的东西。
请您参考如下方法:
在 __init__.py 中创建一个 __all__。
如果您在 functions.py 中已经有了一个 __all__,您可以直接导入它:
from .functions import *
from .functions import __all__
如果您要将多个模块合并在一起,则必须更加冗长
from .functions import *
from .classes import *
from . import functions
from . import classes
__all__ = functions.__all__ + classes.__all__
或者,当然,您始终可以明确:
from .functions import *
__all__ = ['spam', 'eggs']
或者,如果您想动态构建它:
from .functions import *
from . import functions
__all__ = [name for name in dir(functions) if not name.startswith('_')]
... 或(非常 hacky - 但如果您有一个 __init__.py 从大量子模块中收集名称而不做任何其他事情,有时会很有用)...
from .functions import *
__all__ = [name for name in globals() if not name.startswith('_')]
……或者你可以变得非常聪明,按照这种方式做事,例如 multiprocessing做:1
from . import functions
__all__ = [name for name in functions if not name.startswith('_')]
globals().update({name: getattr(functions, name) for name in __all__})
请记住,__all__ 还会影响当有人执行 from Ganymede import *(实际上是 that's the main purpose of __all__ )时发生的情况,以及 检查的内容 和其他工具报告为您的包的公共(public)成员。
我不确定在没有 __all__ 的情况下 help 的行为是否被记录在任何地方(交互式 help 作品仅被轻微记录在general...),它与 import 认为的 public 不太一样。
<子>
1。好吧,
multiprocessing 实际上更聪明/hacky;它不是从子模块中提取属性,而是从该子模块的动态单例属性中提取属性,该子模块在主进程和子进程上设置不同,并相应地更改包的一些顶级函数......
子>
