Pro*_*014 15 python tuples list python-import python-3.x
在许多大型项目中,甚至在Django等项目中,以及在官方 Python 文档中,使用 list 列出文件中“可从外部获得”的模块组件__init__.py:
__all__ = [foo, bar, other]
Run Code Online (Sandbox Code Playgroud)
然而,记录
__all__ = (foo, bar, other)
Run Code Online (Sandbox Code Playgroud)
它也会起作用,理论上它不会显着提高代码性能。
为什么,那就用它来列出?
也许有一些我不知道的神奇 PEP?
Mis*_*agi 13
list使用或没有任何约束力的理由tuple。然而,惯用地表示相同类型的项目list的序列,但表示不同类型的项目的序列。tuple这也是由类型提示编码的,类型提示list[str | int]内部有一些但位置字段tuple[str, int, int]。
因此,list更准确地表示“任意名称序列”。
PEP 8 反复提到是__all__一个列表:
为了更好地支持自省,模块应使用属性在其公共 API 中显式声明名称
__all__。设置__all__为空列表表示该模块没有公共 API。
Run Code Online (Sandbox Code Playgroud)"""This is the example module. This module does stuff. """ ... __all__ = ['a', 'b', 'c']