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
I'm just adding this to be precise:
All other answers refer to modules. The original question explicitely mentioned __all__
in __init__.py
files, so this is about python packages.
Generally, __all__
only comes into play when the from xxx import *
variant of the import
statement is used. This applies to packages as well as to modules.
The behaviour for modules is explained in the other answers. The exact behaviour for packages is described here in detail.
In short, __all__
on package level does approximately the same thing as for modules, except it deals with modules within the package (in contrast to specifying names within the module). So __all__
specifies all modules that shall be loaded and imported into the current namespace when us use from package import *
.
The big difference is, that when you omit the declaration of __all__
in a package's __init__.py
, the statement from package import *
will not import anything at all (with exceptions explained in the documentation, see link above).
On the other hand, if you omit __all__
in a module, the "starred import" will import all names (not starting with an underscore) defined in the module.