In Python, __all__ is a special variable used in a module to explicitly define which names should be imported when you use:

from module import *

By default, this wildcard import pulls in all names that don’t start with an underscore (_). But if __all__ is defined, Python only imports the names listed inside it, giving you full control over what gets exposed.

Why Use __all__?

  • Prevents unwanted or internal functions from being imported.
  • Makes your module’s API cleaner and easier to understand.
  • Helpful for maintaining large projects or packages.

How __all__ Changes Import Behavior

These examples illustrate what happens when you import everything from a module—with and without setting __all__.

Example 1: Without __all__

This example shows how all non-private names are imported by default when __all__ is not defined.

# mymodule.pydef public_func():

    return “I’m public”

 

def _private_func():

    return “I’m private”

from mymodule import *print(public_func())  # Works

print(_private_func()) # Still works (not truly private)

Even though _private_func() starts with an underscore, it’s still accessible.

Also Read: Python Integration in 2025

Example 2 : With __all__

This example demonstrates how __all__ restricts what gets imported using from module import *.

# mymodule.py

__all__ = [‘public_func’]

 

def public_func():

    return “I’m public”

 

def _private_func():

    return “I’m private”

from mymodule import *print(public_func()) # Works

print(_private_func()) # NameError: not defined

Only public_func is imported — _private_func is hidden.

Important Notes

__all__ only affects from module import * — it does not limit access if you import the module directly:

import mymoduleprint(mymodule._private_func()) # Still accessible

It’s mostly useful in packages and module-level API design to restrict what gets pulled in automatically.

Tip

Use __all__ when you want to define a clean, public API for your module, want to hide helper functions, internal variables, or classes from the outside world or working in a team or building libraries meant for reuse.