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
相关产品推荐
相关产品推荐

