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 does?
The __all__ in Python is a list of strings defining what symbols in a module will be exported when from <module> import * is used on the module.
In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.
The __name__ Attribute and the __main__ Scope The Python interpreter automatically adds this value when we are running a Python script or importing our code as a module. The __name__ in Python is a special variable that defines the name of the class or the current module or the script from which it gets invoked.
Python files are called modules and they are identified by the . py file extension. A module can define functions, classes, and variables. So when the interpreter runs a module, the __name__ variable will be set as __main__ if the module that is being run is the main program.
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With