gpt4 book ai didi

python - 为什么要在 python 包的 __init__ 中使用 __all__?

转载 作者:太空宇宙 更新时间:2023-11-03 13:41:06 24 4
gpt4 key购买 nike

我已经读过 Can someone explain __all__ in Python?我知道它只影响 from ... import * 语句,但我想不出一个真正的用例。当我可以简单地避免在 __init__ 命名空间中导入这些名称时,为什么我应该在 __all__ 中重复导出的名称(DRY!)?

例子:

mypackage/__init__.py

from a import A

mypackage/a.py

A = "A"
A1 = "A1"

mypackage/b.py

B = "B"    

然后在 python 中:

>>> from mypackage import *
>>> A
'A'
>>>
>>> A1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'A1' is not defined
>>> b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined

如您所见,A 在命名空间中,但 A1b 不在。为什么我必须定义 __all__ = ["A"]

最佳答案

唯一您想要在包的__init__.py 中定义__all__ 的时间是列出您“导出”的成员的名称想要在用户执行时导出:

from package import *

这记录在 6.4.1. Importing * From a Package

注意:如果您在包中定义__all__,则默认行为如下(来自文档):

If __all__ is not defined, the statement from sound.effects import *does not import all submodules from the package sound.effects into thecurrent namespace; it only ensures that the package sound.effects hasbeen imported (possibly running any initialization code in__init__.py) and then imports whatever names are defined in the package. This includes any names defined (and submodules explicitlyloaded) by __init__.py. It also includes any submodules of the packagethat were explicitly loaded by previous import statements. Considerthis code:

对此的“天真”解释可以是:

If you don't define __all__; a from package import * will bring in everything from that package and anything imported in that pacakge's __init__.py.

关于python - 为什么要在 python 包的 __init__ 中使用 __all__?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30888683/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com