What is __all__ used for in Python?

14

I've seen some Python code whose __init__.py file has a __all__ variable with a list assigned.

Example:

__all__ = ['foo', 'bar']

I've noticed that in Python, when things start with underline , it means that it's some special functionality.

So, I'd like to know what this __all__ is for?

    
asked by anonymous 10.01.2017 / 19:17

1 answer

20
The __all__ must be a list of strings that defines which symbols are exported from a module when from <module> import * is used.

It also serves to make it easier to read the code. Anyone reading the source code will easily know which members are publicly exposed to this module.

For example

Module code

__all__ = ['foo', 'bar']

baz = 5
bar = 10
def foo(): 
    return 'qualquer coisa'

In use

from module import *

print foo()
print bar

# A linha abaixo causará uma exception, porque o membro não foi exportado
print baz

I put the code in GitHub for future reference

If the __all__ of the above example is removed, all members whose name does not start with underline will be imported.

Note : It is important to note that members cited in __all__ will only affect the behavior of import * . Therefore, members not listed in it remain accessible by " import direct". In the example, it would be possible to from modulo import baz and use this value.

    
10.01.2017 / 19:26