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?
views:
5225answers:
8it's a list of public objects of that module -- it overrides the default of hiding everything that begins with an underscore
From (An Unofficial) Python Reference Wiki:
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).
Python documentation links:
- Reference - 6.12 The import statement
- Tutorial - 6.4.1 Importing * From a Package
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.
It also changes what pydoc will show:
module1.py
a = "A"
b = "B"
c = "C"
module2.py
__all__ = ['a', 'b']
a = "A"
b = "B"
c = "C"
$ pydoc module1
Help on module module1:
NAME
module1
FILE
module1.py
DATA
a = 'A'
b = 'B'
c = 'C'
$ pydoc module2
Help on module module2:
NAME
module2
FILE
module2.py
DATA
__all__ = ['a', 'b']
a = 'A'
b = 'B'
I declare __all__ in all my modules, as well as underscore internal details, these really help when using things you've never used before in live interpreter sessions.
@alec thomas
__all__ = ['bar', 'baz'] waz = 5 bar = 10 def baz(): return baz' def baz(): return 'baz'
Small detail: the above code will fail, because 'bar" and 'baz' have to exist before they are added to __all__. The code will work if the definition of __all__ is moved to the end.