Course contentsShow
← Python
Lesson 519 of 1,0608. Professional Tooling and PackagingFree lesson

Defining Explicit Module Boundaries

You will use internal underscore prefixes and __all__ definitions to clearly distinguish between public APIs and private implementation details within your project.

In this lesson, you will learn how to protect your package’s internal logic by defining explicit boundaries between public APIs and private implementation details.

As your projects grow in complexity, it becomes easy to accidentally expose internal helper functions or temporary variables to users of your module. This creates "leaky abstractions," where other developers might start relying on code that you intended to refactor or delete later. Python provides two primary mechanisms to manage these boundaries: the underscore prefix and the __all__ list.

The Underscore Convention

By convention, any name in Python starting with a single underscore (_) is considered internal. While Python does not strictly enforce this at runtime, it signals to other developers—and to IDEs—that the code is private and should not be accessed directly from outside the module.

Controlling Exports with __all__

To explicitly define your public API, you can define a list named __all__ at the top of your module. When a user runs from my_module import *, Python will only import the names listed in __all__. If __all__ is absent, from * imports everything that doesn’t start with an underscore.

Consider this example in a file named processor.py:

# Internal helper function
def _format_data(data):
    return data.strip().lower()

# Public function
def process_input(data):
    return _format_data(data)

# Explicitly defining the public API
__all__ = ["process_input"]

In this setup, someone importing your module can safely use process_input, but the _format_data helper remains hidden. Even if a user tries from processor import *, _format_data will not be imported into their namespace.

By adopting these patterns, you turn your code into a professional API. Users benefit from a cleaner autocomplete experience, and you gain the freedom to modify or rename your internal helper functions without breaking external code.

Key Takeaway: Use single underscores for private internal details and define __all__ to explicitly declare your public API surface area, ensuring your module’s interface remains clean and maintainable.