Python Glossary Русский

all Python 3Modules & importsterm

__all__

import

A list of strings in a module or package: which names from m import * takes and what counts as the public API for docs and linters.

Syntax

__all__ = ['public_func', 'PublicClass']

__all__ does not make names private: import m; m._x and an explicit from m import helper work even when helper is not listed — it affects only the star, help() and tools. Without __all__ the star takes every name not starting with an underscore, including modules imported inside (os, sys), so they leak into the caller. A name in __all__ that the module lacks shows up only on from m import *: it raises AttributeError. In a package's __init__.py, __all__ also lists submodules, and the star imports them; without __all__, from pkg import * loads no submodules at all.

Examples

import sys
sys.path.insert(0, '.')
with open('mylib.py', 'w', encoding='utf-8') as f:
    f.write("__all__ = ['public']\ndef public(): return 'pub'\n"
            "def helper(): return 'help'\ndef _secret(): return 'sec'\n")
from mylib import *
print([n for n in ('public', 'helper', '_secret') if n in globals()])  # → ['public']
from mylib import helper, _secret  # явный импорт __all__ не ограничивает
print(helper(), _secret())  # → help sec
import os, sys
sys.path.insert(0, '.')
os.makedirs('kit', exist_ok=True)
with open('kit/__init__.py', 'w', encoding='utf-8') as f:
    f.write("__all__ = ['a']\n")
for name in ('a', 'b'):
    with open(f'kit/{name}.py', 'w', encoding='utf-8') as f:
        f.write('x = 1\n')
from kit import *
print('a' in globals(), 'b' in globals())  # → True False
import sys
sys.path.insert(0, '.')
with open('broken.py', 'w', encoding='utf-8') as f:
    f.write("__all__ = ['missing']\n")
import broken  # сам импорт проходит
from broken import *  # → AttributeError: module 'broken' has no attribute 'missing'

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy