元组[Any]不满足Type [Any]

问题描述

我注意到Tuple[Any]不满足Type[Any]

python3.8中...

var: Type[Any] = Tuple[Any]

对此我运行mypy时,我得到

Incompatible types in assignment (expression has type "object",variable has type "Type[Any]")

有人知道我在这里做错了什么吗?我的最终目标是能够将var分配给Tuple[Any,...]

谢谢!

解决方法

在静态类型系统中,Tuple[Any]Any的子类型,而Type[Any]的唯一有效值是实际的 runtime 类型,对象是{ {1}}。您可以将type分配给tuple,但不能分配var,因为Tuple[Any]不是Tuple[Any]

,

Tuple 类型提示不等同于tuple 类型本身。比较他们的行为:

>>> from typing import Tuple
>>> tuple()
()
>>> Tuple()
TypeError: Type Tuple cannot be instantiated; use tuple() instead

因此,只有var: Type = tuple是有效的,而var: Type = Tuple的任何变体都是无效的。


自Python3.9起,builtin types and their type hints are unified。这样可以将两者互换使用:

>>> tuple[int]()
()

您可以期望var: Type = tuple[int]可以工作一次mypy PEP 585 support is complete