28

I've seen it a lot in python/Lib source code but I don't know what it is for.

I thought it was used to limit accessible members of of a module. So only the elements at __all__ will show up when dir(module).

I did a little example and saw it was not working as I expected.

So... What's the python __all__ module level variable for?

igauravsehrawat
  • 3,696
  • 3
  • 33
  • 46
Juanjo Conti
  • 28,823
  • 42
  • 111
  • 133
  • 4
    Similar question here: http://stackoverflow.com/questions/44834/can-someone-explain-all-in-python – viam0Zah Jul 28 '11 at 14:41

3 Answers3

52

It has two purposes:

  1. Anybody who reads the source will know what the exposed public API is. It doesn't prevent them from poking around in private declarations, but does provide a good warning not to.

  2. When using from mod import *, only names listed in __all__ will be imported. This is not as important, in my opinion, because importing everything is a really bad idea.

John Millikin
  • 197,344
  • 39
  • 212
  • 226
  • 8
    Not just anybody, also anything. Some api documentation tools respect `__all__`. pydoc does, and I'm pretty sure epydoc and the like also do. – mzz Feb 03 '10 at 00:59
  • The public variables in a '.py' is available in another file when we do a 'import *', even if they are not included in the __all__.can any one please clarify about this..? – Alchemist777 Feb 08 '13 at 04:44
  • Sphinx also respects ``__all__`` – Rafe Apr 20 '13 at 18:31
8

http://docs.python.org/tutorial/modules.html#importing-from-a-package

Now what happens when the user writes from sound.effects import *? Ideally, one would hope that this somehow goes out to the filesystem, finds which submodules are present in the package, and imports them all. This could take a long time and importing sub-modules might have unwanted side-effects that should only happen when the sub-module is explicitly imported.

The only solution is for the package author to provide an explicit index of the package. The import statement uses the following convention: if a package’s __init__.py code defines a list named __all__, it is taken to be the list of module names that should be imported when from package import * is encountered. It is up to the package author to keep this list up-to-date when a new version of the package is released. Package authors may also decide not to support it, if they don’t see a use for importing * from their package.

Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194
4

It controls what you get pulled into your namepsace when you

from blah import *

See Importing * from a Package

John La Rooy
  • 295,403
  • 53
  • 369
  • 502