有人可以用Python解释__all__吗?
时间:2020-03-05 18:47:55 来源:igfitidea点击:
我越来越多地使用Python,并且不断看到在不同的__init __。py
文件中设置的__all__
变量。有人可以解释这是什么吗?
解决方案
回答
这是该模块的公共对象的列表,由import *解释。它覆盖了隐藏所有以下划线开头的所有内容的默认设置。
回答
从(非官方)Python参考Wiki:
The public names defined by a module are determined by checking the module's namespace for a variable named __all__; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in __all__ are all considered public and are required to exist. If __all__ is not defined, the set of public names includes all names found in the module's namespace which do not begin with an underscore character ("_"). __all__ should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).
回答
链接到此处但未明确提及的是使用__all__
的确切时间。它是一个字符串列表,定义了在模块上使用from <module> import *
时将导出模块中的哪些符号。
例如,以下foo.py中的代码显式导出符号bar和baz:
__all__ = ['bar', 'baz'] waz = 5 bar = 10 def baz(): return 'baz'
然后可以像下面这样导入这些符号:
from foo import * print bar print baz # The following will trigger an exception, as "waz" is not exported by the module print waz
如果上面的__all__被注释掉,则此代码将执行到完成,因为import *的默认行为是从给定的命名空间中导入所有不以下划线开头的符号。
参考:https://docs.python.org/3.5/tutorial/modules.html#importing-from-a-package
注意:__all__
仅影响from from <module> import *`行为。 __all__中未提及的成员仍然可以从模块外部访问,并且可以从<module> import <member>中导入。
回答
它还更改了pydoc将显示的内容:
module1.py
a = "A" b = "B" c = "C"
module2.py
__all__ = ['a', 'b'] a = "A" b = "B" c = "C"
$ pydoc module1
Help on module module1: NAME module1 FILE module1.py DATA a = 'A' b = 'B' c = 'C'
$ pydoc module2
Help on module module2: NAME module2 FILE module2.py DATA __all__ = ['a', 'b'] a = 'A' b = 'B'
我在所有模块中都声明了" all",并强调了内部细节,这些在使用实时解释器会话中从未使用过的功能时确实很有帮助。