I've seen some code written in Python whose
__init__.py file had a
__all__ variable with a
list assigned to it.
__all__ = ['foo', 'bar']
I've noticed that in Python, when things start with an
underline , it means it's some special functionality.
So I would like to know what this
__all__ is for?
__all__ must be a list of
strings that define which symbols will be exported from a module when using
from <module> import * .
It also makes it easier to read the code. Anyone reading the source code will easily know what the publicly exposed members of this module are.
__all__ = ['foo', 'bar'] baz = 5 bar = 10 def foo(): return 'qualquer coisa'
from module import * print foo() print bar # A linha abaixo causará uma exception, porque o membro não foi exportado print baz
__all__ in the above example is removed, all members whose name does not start with an underscore will be imported.
Note : It is important to note that the members quoted in
__all__ will only affect the behavior of
import * . Therefore, the members not mentioned in it are still accessible by "direct import ". In the example, it would be possible to do
from modulo import baz and use this value.