0
0
PythonConceptBeginner · 3 min read

__all__ in Python: Purpose and Usage Explained

__all__ is a special list in a Python module that defines which names should be imported when using from module import *. It controls what is publicly accessible from the module, helping to keep internal details private.
⚙️

How It Works

Imagine a Python module as a toolbox. It contains many tools (functions, classes, variables), but you might want to show only some of them to others. The __all__ list is like a label on the toolbox that says which tools are available when someone grabs everything at once.

When you write from module import *, Python looks for __all__ in that module. If it exists, Python imports only the names listed there. If __all__ is missing, Python imports all names that don’t start with an underscore (_), which are considered private by convention.

This helps keep your module clean and hides internal parts that users don’t need to see or use.

💻

Example

This example shows a module defining __all__ to control what gets imported with from module import *.

python
## file: mymodule.py
__all__ = ['public_function']

def public_function():
    return 'This is public'

def _private_function():
    return 'This is private'


# In another file or interactive shell
from mymodule import *

print(public_function())

try:
    print(_private_function())
except NameError:
    print('_private_function is not accessible')
Output
This is public _private_function is not accessible
🎯

When to Use

Use __all__ when you want to clearly define the public interface of your module. It helps other programmers know which parts of your code are safe to use and which are internal details.

For example, in large projects or libraries, __all__ prevents accidental use of internal functions that might change or break. It also makes your module easier to maintain and understand.

Key Points

  • __all__ is a list of strings naming public objects in a module.
  • It controls what from module import * imports.
  • If missing, Python imports all names not starting with an underscore.
  • It helps hide internal details and keeps code clean.

Key Takeaways

__all__ defines the public API of a Python module.
It controls what names are imported with from module import *.
Without __all__, all non-underscore names are imported by default.
Use __all__ to hide internal functions and keep your module clean.
It improves code readability and maintenance in larger projects.