Python文档中__init__.py的__all__为何定义为列表而非元组?
__all__ in __init__.py uses a list instead of a tuple? Great question! This is one of those subtle Python design choices that makes you pause—especially since tuples do work perfectly well here. Let’s break down the key reasons behind this convention:
Community convention & readability
In Python, lists are universally associated with "collections of similar items that might change", while tuples are often seen as "immutable, structured records". Even though__all__is almost always defined once and never modified, using a list aligns with the intuitive idea that this is a set of names to expose—a collection of related elements, not a fixed, unchangeable structure. Most official docs, tutorials, and third-party libraries stick to lists for__all__, so it’s become the expected pattern that new developers learn and recognize immediately.Historical context
Early Python design favored lists for groups of homogeneous items (like strings representing function/class names) and tuples for heterogeneous data. When__all__was introduced, using a list felt more natural for a collection of exportable names. There’s no strong technical reason to avoid tuples here, but the convention stuck simply because lists were the go-to choice for this kind of use case back then.Flexibility for dynamic use cases
While rare, there are scenarios where you might want to build__all__dynamically. For example, adding platform-specific functions or conditional exports:__all__ = ["core_function"] if sys.platform == "linux": __all__.append("linux_opt_feature")A list’s mutability makes this kind of incremental update straightforward. With a tuple, you’d have to reassign the entire variable (like
__all__ += ("linux_opt_feature",)), which works but feels clunkier compared toappend().
It’s worth noting that using a tuple for __all__ isn’t wrong—Python will process it without any issues. The choice is purely about convention, readability, and minor flexibility edge cases. At the end of the day, both types achieve the same goal; lists just happen to be the de facto standard.
内容的提问来源于stack exchange,提问作者Mnich

