What is __all__ in Python for?

Asked

Viewed 1,890 times

16

I’ve seen some code written in Python whose file __init__.py had a variable __all__ with a list assigned.

Example:

__all__ = ['foo', 'bar']

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

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

  • _ sometimes does not refer to a special feature, since python has no scope (private, public) they usually use _ to indicate private attributes and method.

1 answer

25


The __all__ should be a list of strings defining which symbols will be exported from a module when used from <module> import *.

It also serves to facilitate the reading of 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 on Github for future reference

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.