【发布时间】:2021-08-07 19:25:39
【问题描述】:
我有下面的例子。
from typing import Union, TypeVar, Dict, Sequence
IdentifierSymbol = TypeVar("IdentifierSymbol", str, int)
def f(ids: Sequence[IdentifierSymbol]) -> Dict[int, IdentifierSymbol]:
return dict(zip(range(len(ids)), ids))
def g(ids: Union[Sequence[int], Sequence[str]]) -> int:
x = f(ids)
return 1
PyLance(我猜在里面使用 mypy)在x=f(ids) 行中抱怨以下内容:
Argument of type "Sequence[int] | Sequence[str]" cannot be assigned to parameter "ids" of type "Sequence[IdentifierSymbol@f]" in function "f"
Type "Sequence[int] | Sequence[str]" cannot be assigned to type "Sequence[IdentifierSymbol@f]"
TypeVar "_T_co@Sequence" is covariant
Type "str" is not compatible with constrained type "int" PylancereportGeneralTypeIssues
我不确定如何解释,但听起来问题是 int 与 str 不兼容。但为什么在这种情况下这是一个问题?我要么是strs序列,要么是ints序列,int和str的兼容性哪来的?
【问题讨论】:
-
请注意,mypy 在此处失败并出现不同的错误:
Value of type variable "IdentifierSymbol" of "f" cannot be "object"。 IIRC MyPy 通过超类型而不是 Union 解析了一个可以被两种类型占据的变量。 -
@MisterMiyagi Huh 我猜 PyLance 有自己的类型检查器。对此感到惊讶。很可能 Union[Sequence[int], Sequence[str]] 解析为 Sequence[object] 或类似的东西,然后什么也找不到。
标签: python python-3.x type-hinting python-typing