Python 的协变、逆变与不变
2024 5 29 07:45 PM 0 条评论 243 次查看
ProxiesTypes
:URLTypes = Union["URL", str]
ProxyTypes = Union[URLTypes, "Proxy"]
ProxiesTypes = Union[ProxyTypes, Dict[URLTypes, Union[None, ProxyTypes]]]
可以看出,dict[str, str]
应该是符合它的参数签名的,然而我传入一个 dict[str, str]
参数后,Pylance 却会报错,这让我大为不解。于是我又尝试简化了一下这个问题:
from typing import Mapping
a: dict[int, int] = {}
b: dict[int, int | str] = a # error:
# Expression of type "dict[int, int]" is incompatible with declared type "dict[int, int | str]"
# "dict[int, int]" is incompatible with "dict[int, int | str]"
# Type parameter "_VT@dict" is invariant, but "int" is not the same as "int | str"
# Consider switching from "dict" to "Mapping" which is covariant in the value type
c: Mapping[int, int | str] = a
d: Mapping[int | str, int] = a # error:
# Expression of type "dict[int, int]" is incompatible with declared type "Mapping[int | str, int]"
# "dict[int, int]" is incompatible with "Mapping[int | str, int]"
# Type parameter "_KT@Mapping" is invariant, but "int" is not the same as "int | str"
是不是很奇怪,为啥 dict[int, int]
和 dict[int, int | str]
或 Mapping[int | str, int]
都不兼容,而与 Mapping[int, int | str]
兼容?