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
__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.pathor 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__.pycode defines a list named__all__, it is taken to be the list of module names that should be imported whenfrom package import *is encountered.