I have been using Python more and more, and I keep seeing the variable __all__
set in different __init__.py
files.
(我越来越多地使用Python,并且不断看到在不同的__init__.py
文件中设置了变量__all__
。)
(有人可以解释这是什么吗?)
ask by varikin translate from so I have been using Python more and more, and I keep seeing the variable __all__
set in different __init__.py
files.
(我越来越多地使用Python,并且不断看到在不同的__init__.py
文件中设置了变量__all__
。)
(有人可以解释这是什么吗?)
ask by varikin translate from so Linked to, but not explicitly mentioned here, is exactly when __all__
is used.
(链接到__all__
确切时间是在此处,但未明确提及。)
from <module> import *
is used on the module. (它是一个字符串列表,用于定义在模块上使用from <module> import *
时将在模块中导出哪些符号。)
For example, the following code in a foo.py
explicitly exports the symbols bar
and baz
:
(例如, foo.py
的以下代码显式导出符号bar
和baz
:)
__all__ = ['bar', 'baz']
waz = 5
bar = 10
def baz(): return 'baz'
These symbols can then be imported like so:
(然后可以像下面这样导入这些符号:)
from foo import *
print(bar)
print(baz)
# The following will trigger an exception, as "waz" is not exported by the module
print(waz)
If the __all__
above is commented out, this code will then execute to completion, as the default behaviour of import *
is to import all symbols that do not begin with an underscore, from the given namespace.
(如果上面的__all__
被注释掉,则此代码将执行完成,因为import *
的默认行为是从给定的命名空间中导入所有不以下划线开头的符号。)
Reference: https://docs.python.org/tutorial/modules.html#importing-from-a-package
(参考: https : //docs.python.org/tutorial/modules.html#importing-from-a-package)
NOTE: __all__
affects the from <module> import *
behavior only.
(注意: __all__
影响from <module> import *
行为。)
__all__
are still accessible from outside the module and can be imported with from <module> import <member>
. (__all__
中未提及的成员仍然可以从模块外部访问,并且可以通过from <module> import <member>
。)