Python › Modules & Packaging

What is __all__ and how does it control `from module import *` behavior?

Intermediate

Answer

__all__ is a list of strings defined at module level specifying exactly which names are exported when a client does `from module import *`. Without __all__, `import *` imports all public names (those not starting with an underscore); with __all__ defined, only the listed names are imported, giving the module author explicit control over its public API surface.
# mymodule.py
__all__ = ['public_func', 'PublicClass']

def public_func(): pass
def _private_helper(): pass
class PublicClass: pass

# from mymodule import *  only imports public_func and PublicClass
Real-world example A utility module defines __all__ to explicitly exclude internal helper functions from wildcard imports, keeping the importing namespace clean and preventing accidental use of implementation details.

Common follow-ups: Does __all__ affect explicit `from module import _private`?;Why is `import *` generally discouraged regardless?