By varikin

2008-09-04 21:28:18 8 Comments

I have been using Python more and more, and I keep seeing the variable __all__ set in different files. Can someone explain what this does?


@Aaron Hall 2016-02-29 21:58:50

Explain __all__ in Python?

I keep seeing the variable __all__ set in different files.

What does this do?

What does __all__ do?

It declares the semantically "public" names from a module. If there is a name in __all__, users are expected to use it, and they can have the expectation that it will not change.

It also will have programmatic affects:

import *

__all__ in a module, e.g.

__all__ = ['foo', 'Bar']

means that when you import * from the module, only those names in the __all__ are imported:

from module import *               # imports foo and Bar

Documentation tools

Documentation and code autocompletion tools may (in fact, should) also inspect the __all__ to determine what names to show as available from a module. makes a directory a Python package

From the docs:

The files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

In the simplest case, can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable.

So the can declare the __all__ for a package.

Managing an API:

A package is typically made up of modules that may import one another, but that are necessarily tied together with an file. That file is what makes the directory an actual Python package. For example, say you have the following files in a package:


Let's create these files with Python so you can follow along - you could paste the following into a Python 3 shell:

from pathlib import Path

package = Path('package')

(package / '').write_text("""
from .module_1 import *
from .module_2 import *

package_module_1 = package / ''
__all__ = ['foo']
imp_detail1 = imp_detail2 = imp_detail3 = None
def foo(): pass

package_module_2 = package / ''
__all__ = ['Bar']
imp_detail1 = imp_detail2 = imp_detail3 = None
class Bar: pass

And now you have presented a complete api that someone else can use when they import your package, like so:

import package

And the package won't have all the other implementation details you used when creating your modules cluttering up the package namespace.

__all__ in

After more work, maybe you've decided that the modules are too big (like many thousands of lines?) and need to be split up. So you do the following:

├── module_1
│   ├──
│   └──
└── module_2

First make the subpackage directories with the same names as the modules:

subpackage_1 = package / 'module_1'
subpackage_2 = package / 'module_2'

Move the implementations:

package_module_1.rename(subpackage_1 / '')
package_module_2.rename(subpackage_2 / '')

create __init__.pys for the subpackages that declare the __all__ for each:

(subpackage_1 / '').write_text("""
from .foo_implementation import *
__all__ = ['foo']
(subpackage_2 / '').write_text("""
from .Bar_implementation import *
__all__ = ['Bar']

And now you still have the api provisioned at the package level:

>>> import package
>>> package.Bar()
<package.module_2.Bar_implementation.Bar object at 0x7f0c2349d210>

And you can easily add things to your API that you can manage at the subpackage level instead of the subpackage's module level. If you want to add a new name to the API, you simply update the, e.g. in module_2:

from .Bar_implementation import *
from .Baz_implementation import *
__all__ = ['Bar', 'Baz']

And if you're not ready to publish Baz in the top level API, in your top level you could have:

from .module_1 import *       # also constrained by __all__'s
from .module_2 import *       # in the's
__all__ = ['foo', 'Bar']     # further constraining the names advertised

and if your users are aware of the availability of Baz, they can use it:

import package

but if they don't know about it, other tools (like pydoc) won't inform them.

You can later change that when Baz is ready for prime time:

from .module_1 import *
from .module_2 import *
__all__ = ['foo', 'Bar', 'Baz']

Prefixing _ versus __all__:

By default, Python will export all names that do not start with an _. You certainly could rely on this mechanism. Some packages in the Python standard library, in fact, do rely on this, but to do so, they alias their imports, for example, in ctypes/

import os as _os, sys as _sys

Using the _ convention can be more elegant because it removes the redundancy of naming the names again. But it adds the redundancy for imports (if you have a lot of them) and it is easy to forget to do this consistently - and the last thing you want is to have to indefinitely support something you intended to only be an implementation detail, just because you forgot to prefix an _ when naming a function.

I personally write an __all__ early in my development lifecycle for modules so that others who might use my code know what they should use and not use.

Most packages in the standard library also use __all__.

When avoiding __all__ makes sense

It makes sense to stick to the _ prefix convention in lieu of __all__ when:

  • You're still in early development mode and have no users, and are constantly tweaking your API.
  • Maybe you do have users, but you have unittests that cover the API, and you're still actively adding to the API and tweaking in development.

An export decorator

The downside of using __all__ is that you have to write the names of functions and classes being exported twice - and the information is kept separate from the definitions. We could use a decorator to solve this problem.

I got the idea for such an export decorator from David Beazley's talk on packaging. This implementation seems to work well in CPython's traditional importer. If you have a special import hook or system, I do not guarantee it, but if you adopt it, it is fairly trivial to back out - you'll just need to manually add the names back into the __all__

So in, for example, a utility library, you would define the decorator:

import sys

def export(fn):
    mod = sys.modules[fn.__module__]
    if hasattr(mod, '__all__'):
        mod.__all__ = [fn.__name__]
    return fn

and then, where you would define an __all__, you do this:

$ cat >
from lib import export
__all__ = [] # optional - we create a list if __all__ is not there.

def foo(): pass

def bar():

def main():

if __name__ == '__main__':

And this works fine whether run as main or imported by another function.

$ cat >
import main

$ python

And API provisioning with import * will work too:

$ cat >
from main import *
main() # expected to error here, not exported

$ python
Traceback (most recent call last):
  File "", line 4, in <module>
    main() # expected to error here, not exported
NameError: name 'main' is not defined

@MvG 2017-01-27 13:58:15

Cross reference: I mentioned your decorator in this CW answer to the question of how to write an @export decorator.

@Brett Reinhard 2017-11-07 04:21:46

This has single handedly been the most helpful answer I have seen in regards to helping a relatively new python developer understand the process of importing modules/packages with and the use of __all__

@Mike C 2019-08-12 16:32:43

This helps me a lot. My problem, tho, is that the submodules I want to import are all generated files with a lot of cruft in their symbols that I'd like to strip out, without having to manually ensure that __all__ is correct.

@Aaron Hall 2019-08-12 17:22:21

@MikeC then maybe you should generate your __all__ too - but then I would say you have an unstable API... This would be something to have some comprehensive acceptance tests on.

@Mike C 2019-08-12 23:07:52

@AaronHall "they won't have all the other names ... cluttering up the package namespace" But they will have the names module_1 and module_2; is it OK to include an explicit del module_1 in Am I wrong to think this is worthwhile?

@Bob Stein 2016-03-20 20:20:43

__all__ customizes * in from <module> import *

__all__ customizes * in from <package> import *

A module is a .py file meant to be imported.

A package is a directory with a file. A package usually contains modules.


""" - an example module """

__all__ = ['swiss', 'cheddar']

swiss = 4.99
cheddar = 3.99
gouda = 10.99

__all__ lets humans know the "public" features of a module.[@AaronHall] Also, pydoc recognizes them.[@Longpoke]

from module import *

See how swiss and cheddar are brought into the local namespace, but not gouda:

>>> from cheese import *
>>> swiss, cheddar
(4.99, 3.99)
>>> gouda
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'gouda' is not defined

Without __all__, any symbol (that doesn't start with an underscore) would have been available.

Imports without * are not affected by __all__

import module

>>> import cheese
>>>, cheese.cheddar, cheese.gouda
(4.99, 3.99, 10.99)

from module import names

>>> from cheese import swiss, cheddar, gouda
>>> swiss, cheddar, gouda
(4.99, 3.99, 10.99)

import module as localname

>>> import cheese as ch
>>>, ch.cheddar, ch.gouda
(4.99, 3.99, 10.99)


In the file of a package __all__ is a list of strings with the names of public modules or other objects. Those features are available to wildcard imports. As with modules, __all__ customizes the * when wildcard-importing from the package.[@MartinStettner]

Here's an excerpt from the Python MySQL Connector

__all__ = [
    'MySQLConnection', 'Connect', 'custom_error_exception',

    # Some useful constants
    'FieldType', 'FieldFlag', 'ClientFlag', 'CharacterSet', 'RefreshOption',

    # Error handling
    'Error', 'Warning',



The default case, asterisk with no __all__ for a package, is complicated, because the obvious behavior would be expensive: to use the file system to search for all modules in the package. Instead, in my reading of the docs, only the objects defined in are imported:

If __all__ is not defined, the statement from sound.effects import * does not import all submodules from the package sound.effects into the current namespace; it only ensures that the package sound.effects has been imported (possibly running any initialization code in and then imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by It also includes any submodules of the package that were explicitly loaded by previous import statements.

Wildcard imports ... should be avoided as they [confuse] readers and many automated tools.

[PEP 8, @ToolmakerSteve]

@Jatimir 2019-03-21 15:09:16

I really like this answer, but I'm missing the information on what's the default behavior for from <package> import * without __all__ in that is not importing any of the modules.

@Bob Stein 2019-03-21 17:55:08

Thanks @Jatimir, I clarified as best I could without running experiments. I almost wanted to say this case (asterisk without all for a package) behaves the same as if were a module. But I'm not sure that's accurate, or in particular if underscore-prefixed objects are excluded. Also, I more clearly separated the sections on MODULES and PACKAGES. Your thoughts?

@Eugene Yarmash 2019-01-09 14:48:45

__all__ affects how from foo import * works.

Code that is inside a module body (but not in the body of a function or class) may use an asterisk (*) in a from statement:

from foo import *

The * requests that all attributes of module foo be bound as global variables in the importing module. When foo has an attribute __all__, the attribute's value is the list of the names that are bound by this type of from statement. Otherwise, this type of from statement binds all attributes of foo except those beginning with underscores.

Note that __all__ doesn't have to be a list. As per the documentation on the import statement, if defined, __all__ must be a sequence of strings which are names defined or imported by the module. So you may as well use a tuple to save some memory and CPU cycles. Just don't forget a comma in case the module defines a single public name:

__all__ = ('some_name',)

See also Why is “import *” bad?

@prosti 2019-06-17 17:55:21

This is defined in PEP8 here:

Global Variable Names

(Let's hope that these variables are meant for use inside one module only.) The conventions are about the same as those for functions.

Modules that are designed for use via from M import * should use the __all__ mechanism to prevent exporting globals, or use the older convention of prefixing such globals with an underscore (which you might want to do to indicate these globals are "module non-public").

PEP8 provides coding conventions for the Python code comprising the standard library in the main Python distribution. The more you follow this, closer you are to the original intent.

@Alec Thomas 2008-09-15 15:49:50

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 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 *


# The following will trigger an exception, as "waz" is not exported by the module

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.


NOTE: __all__ affects the from <module> import * behavior only. Members that are not mentioned in __all__ are still accessible from outside the module and can be imported with from <module> import <member>.

@Cyker 2018-04-03 01:19:41

Short answer

__all__ affects from <module> import * statements.

Long answer

Consider this example:


In foo/

  • (Implicit) If we don't define __all__, then from foo import * will only import names defined in foo/

  • (Explicit) If we define __all__ = [], then from foo import * will import nothing.

  • (Explicit) If we define __all__ = [ <name1>, ... ], then from foo import * will only import those names.

Note that in the implicit case, python won't import names starting with _. However, you can force importing such names using __all__.

You can view the Python document here.

@Mihai Capotă 2016-04-26 01:39:25

__all__ is used to document the public API of a Python module. Although it is optional, __all__ should be used.

Here is the relevant excerpt from the Python language reference:

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).

PEP 8 uses similar wording, although it also makes it clear that imported names are not part of the public API when __all__ is absent:

To better support introspection, modules should explicitly declare the names in their public API using the __all__ attribute. Setting __all__ to an empty list indicates that the module has no public API.


Imported names should always be considered an implementation detail. Other modules must not rely on indirect access to such imported names unless they are an explicitly documented part of the containing module's API, such as os.path or a package's __init__ module that exposes functionality from submodules.

Furthermore, as pointed out in other answers, __all__ is used to enable wildcard importing for packages:

The import statement uses the following convention: if a package’s 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.

@Jimmy 2008-09-04 21:30:46

It's a list of public objects of that module, as interpreted by import *. It overrides the default of hiding everything that begins with an underscore.

@Brandon Rhodes 2009-12-08 18:40:42

Objects that begin with an underscore, or are not mentioned in __all__ if __all__ is present, are not exactly hidden; they can be seen and accessed perfectly normally if you know their names. It is only in the case of an "import *", which is not recommended anyway, that the distinction carries any weight.

@flying sheep 2012-04-07 22:15:09

@BrandonRhodes: that’s not exactly true either: It’s recommended to only import modules that you know to be designed for import * (like e.g. tk). A good hint if this is the case is the presence of __all__ or names starting with underscore in the module’s code.

@debug 2018-04-10 15:20:10

Public and internal interfaces -, To better support introspection, modules should explicitly declare the names in their public API using the __all__ attribute. Setting __all__ to an empty list indicates that the module has no public API.

@chepner 2019-11-06 15:36:46

I'm not sure that if tk were released today (or in 2012, even), the recommended practice would be to use from tk import *. I think the practice is accepted due to inertia, not intentional design.

@duhaime 2019-11-26 17:16:40

As BrandonRhodes points out this really isn't correct

@MartinStettner 2013-05-16 19:01:48

I'm just adding this to be precise:

All other answers refer to modules. The original question explicitely mentioned __all__ in files, so this is about python packages.

Generally, __all__ only comes into play when the from xxx import * variant of the import statement is used. This applies to packages as well as to modules.

The behaviour for modules is explained in the other answers. The exact behaviour for packages is described here in detail.

In short, __all__ on package level does approximately the same thing as for modules, except it deals with modules within the package (in contrast to specifying names within the module). So __all__ specifies all modules that shall be loaded and imported into the current namespace when us use from package import *.

The big difference is, that when you omit the declaration of __all__ in a package's, the statement from package import * will not import anything at all (with exceptions explained in the documentation, see link above).

On the other hand, if you omit __all__ in a module, the "starred import" will import all names (not starting with an underscore) defined in the module.

@Nikratio 2014-07-20 19:37:31

from package import * will still import everything defined in, even if there is no all. The important difference is that without __all__ it will not automatically import any modules defined in package's directory.

@variable 2019-10-12 05:26:10

When all contains [foo, bar] and in file if we use: from package import *, then, do foo and bar get imported in the local namespace of or in the foo and bars own namespace?

@Lasse V. Karlsen 2008-09-04 21:31:16

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).

@JayRizzo 2018-08-06 03:09:48

The listed link is dead. but found text verbatim on… & here:

@L̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳ 2010-05-15 03:22:29

It also changes what pydoc will show:

a = "A"
b = "B"
c = "C"

__all__ = ['a', 'b']

a = "A"
b = "B"
c = "C"

$ pydoc module1

Help on module module1:



    a = 'A'
    b = 'B'
    c = 'C'

$ pydoc module2

Help on module module2:



    __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.

Related Questions

Sponsored Content

18 Answered Questions

[SOLVED] What are metaclasses in Python?

23 Answered Questions

[SOLVED] Does Python have a ternary conditional operator?

32 Answered Questions

[SOLVED] "Least Astonishment" and the Mutable Default Argument

10 Answered Questions

[SOLVED] Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

63 Answered Questions

[SOLVED] Calling an external command from Python

15 Answered Questions

[SOLVED] What is the meaning of a single and a double underscore before an object name?

13 Answered Questions

[SOLVED] How can I make a time delay in Python?

44 Answered Questions

[SOLVED] Replacements for switch statement in Python?

38 Answered Questions

[SOLVED] var functionName = function() {} vs function functionName() {}

12 Answered Questions

[SOLVED] Meaning of @classmethod and @staticmethod for beginner?

Sponsored Content