Reusable Packages, __init__.py & __all__ API Control
1Concept
A package is a directory containing modules. `__init__.py` marks the directory as an importable package and controls public exports. Defining `__all__ = ['SymbolA', 'SymbolB']` restricts what is imported when clients write `from package import *`.
2Architecture Diagram
package/ ├── __init__.py (__all__ = ['PublicApi']) ├── api.py (Public class PublicApi) └── internal.py (Private helpers hidden from client)
3Code Example
Python 3.12
# Simulating package __all__ boundary control
__all__ = ['PublicService', 'public_function']
class PublicService:
pass
def public_function():
return "Public API"
def _internal_helper():
return "Hidden Helper"
print(f"Exported Public Symbols: {__all__}")
print(f"Has PublicService: {'PublicService' in __all__}")4Expected Output
Exported Public Symbols: ['PublicService', 'public_function'] Has PublicService: True
5Key Takeaways
- ✓`__all__` acts as a contract for library authors to signal intended public API boundaries.
- ✓Avoid `from module import *` in production code; it pollutes namespaces and masks linter errors.
- ✓`__init__.py` can be empty in modern Python (PEP 420).