Can someone explain __all__ in Python?

前端 未结 11 2425
一个人的身影
一个人的身影 2020-11-21 13:36

I have been using Python more and more, and I keep seeing the variable __all__ set in different __init__.py files. Can someone explain what this d

11条回答
  •  孤独总比滥情好
    2020-11-21 13:51

    __all__ is used to document the public API of a Python module. Although it is optional, __all__ should be used.

    Here is the relevant excerpt from the Python language reference:

    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).

    PEP 8 uses similar wording, although it also makes it clear that imported names are not part of the public API when __all__ is absent:

    To better support introspection, modules should explicitly declare the names in their public API using the __all__ attribute. Setting __all__ to an empty list indicates that the module has no public API.

    [...]

    Imported names should always be considered an implementation detail. Other modules must not rely on indirect access to such imported names unless they are an explicitly documented part of the containing module's API, such as os.path or a package's __init__ module that exposes functionality from submodules.

    Furthermore, as pointed out in other answers, __all__ is used to enable wildcard importing for packages:

    The import statement uses the following convention: if a package’s __init__.py code defines a list named __all__, it is taken to be the list of module names that should be imported when from package import * is encountered.

提交回复
热议问题