为什么 __all__ 应该只包含字符串对象?

Why should __all__ only contain string objects?

今天我遇到了以下 pylint 错误:

invalid-all-object (E0604):

Invalid object %r in __all__, must contain only strings Used when an invalid (non-string) object occurs in __all__.

而且我很好奇为什么直接公开对象被认为是不正确的?

如果您公开字符串以外的内容,Python 将抛出异常。这就是pylint报错的原因,因为代码不正确。

文件mymodule.py:

def func():
    pass
__all__ = [func]

现在运行:

from mymodule import *

您将获得 TypeError.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: attribute name must be string, not 'function'

原因是__all__用于命名模块对象上的属性。这就是机制的运作方式。如果你想修改 Python 的导入机制,这样你就可以把对象放在那里,我想你可以,但它只适用于某些类型的对象(函数和 类 可以,但是常数将不起作用,您将无法重命名函数和 类).

因为它应该是 名称 的列表,而不是值:

If the list of identifiers is replaced by a star ('*'), all public names defined in the module are bound in the local namespace for the scope where the import statement occurs.

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). [Language Reference]