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

Python typing模块中Tuple等类型别名为何兼具实例与类特性?

Python typing模块中Tuple这类类型别名的工作原理
  • 它们的构造函数可接收参数,因此表现得像实例对象
  • 但同时也表现得像类对象:普通tuple实例能通过isinstance((1,2,3), Tuple)检查,返回True
  • Python类型检查器(如PyLance)认可somevar : Tuple为合法类型注解

它们能同时作为类和实例使用,以下代码是合法的:

import typing

class Foo(object):
    fixedargs : typing.Tuple

这让它看起来像类,但实际上它是_TupleType的实例,而_TupleType是_SpecialGenericAlias的子类:

>>> import typing
>>>
>>> a = (3,4,5)
>>> isinstance(a, typing.Tuple)
True
>>> type(typing.Tuple)
<class 'typing._TupleType'>

typing.py中的关键实现代码如下:

class _TupleType(_SpecialGenericAlias, _root=True):
    @_tp_cache
    def __getitem__(self, params):
        if not isinstance(params, tuple):
            params = (params,)
        if len(params) >= 2 and params[-1] is ...:
            msg = "Tuple[t, ...]: t must be a type."
            params = tuple(_type_check(p, msg) for p in params[:-1])
            return self.copy_with((*params, _TypingEllipsis))
        msg = "Tuple[t0, t1, ...]: each t must be a type."
        params = tuple(_type_check(p, msg) for p in params)
        return self.copy_with(params)

....

_alias = _SpecialGenericAlias

...

Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
Tuple.__doc__ = \
    """Deprecated alias to builtins.tuple.

    Tuple[X, Y] is the cross-product type of X and Y.

    Example: Tuple[T1, T2] is a tuple of two elements corresponding
    to type variables T1 and T2.  Tuple[int, float, str] is a tuple
    of an int, a float and a string.

    To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
    """
List = _alias(list, 1, inst=False, name='List')
Deque = _alias(collections.deque, 1, name='Deque')
Set = _alias(set, 1, inst=False, name='Set')

此前一直在摸索类型注解如何存储实例数据,现在发现PEP-593和typing.Annotated正是所需的相关技术,可随时关闭此问题。

内容的提问来源于stack exchange,提问作者Jason S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.11 16:05:03