You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python文档中__init__.py的__all__为何定义为列表而非元组?

Why __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 to append().

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:34:47