Can someone explain __all__ in Python?
Linked to, but not explicitly mentioned here, is exactly when __all__
is used. It is a list of strings defining what symbols in a module will be exported when from <module> import *
is used on the module.
For example, the following code in a foo.py
explicitly exports the symbols bar
and baz
:
__all__ = ['bar', 'baz']
waz = 5
bar = 10
def baz(): return 'baz'
These symbols can then be imported like so:
from foo import *
print(bar)
print(baz)
# The following will trigger an exception, as "waz" is not exported by the module
print(waz)
If the __all__
above is commented out, this code will then execute to completion, as the default behaviour of import *
is to import all symbols that do not begin with an underscore, from the given namespace.
Reference: https://docs.python.org/tutorial/modules.html#importing-from-a-package
NOTE: __all__
affects the from <module> import *
behavior only. Members that are not mentioned in __all__
are still accessible from outside the module and can be imported with from <module> import <member>
.
It's a list of public objects of that module, as interpreted by import *
. It overrides the default of hiding everything that begins with an underscore.