In this lesson, you will learn how to use the __all__ variable to strictly control which items are exposed when a user performs a wildcard import on your module.
Why Control Exports?
When you build a module, you often create helper functions or temporary variables that are intended for internal use only. However, when another developer runs from my_module import *, Python automatically imports everything that doesn’t start with an underscore. This can clutter the user's namespace and lead to accidental name collisions.
Using __all__
To solve this, you can define a special list named __all__ at the top of your module. This list acts as a "whitelist." If __all__ is present, Python will only export the names explicitly listed there when a wildcard import is performed.
Consider a file named math_tools.py:
# math_tools.py
def add(a, b):
return a + b
def _internal_helper():
return "This is private"
def subtract(a, b):
return a - b
# Only 'add' and 'subtract' will be exported via wildcard import
__all__ = ["add", "subtract"]
How It Works
If another developer imports your code using from math_tools import *:
- The function
addwill be available. - The function
subtractwill be available. - The function
_internal_helperwill not be available, even though it doesn't start with an underscore, because it is missing from__all__.
Explicitly naming what should be public makes your module much cleaner. It informs other developers exactly which parts of your code are meant to be part of the stable public API and which parts are private implementation details.
Note that __all__ only affects the from module import * syntax; users can still import functions manually (e.g., from math_tools import _internal_helper), but your explicit __all__ list serves as a clear signal of your module's design intentions.
Key Takeaway: Defining an __all__ list in your module creates a whitelist that restricts which names are imported during a wildcard import, helping you maintain a clean and predictable public API.