我正在尝试输入一本可能会有所不同的字典 - 并认为
Mapping, Hashable
的工作原理如下:
from typing import Hashable, Mapping
def f(x : Mapping[Hashable, str]) -> None:
print(x)
_dict = {'hello' : 'something'}
f(x = _dict)
错误:
main.py:9: error: Argument "x" to "f" has incompatible type "Dict[str, str]"; expected "Mapping[Hashable, str]"
Found 1 error in 1 file (checked 1 source file)
我不明白这个错误的原因,我已经向它传递了一个“映射”类型的字典? (https://mypy.readthedocs.io/en/stable/builtin_types.html)。而且密钥是可散列的,我认为这是一种
Hashable
。
当我浏览这些部分时 - 它们看起来都不错,所以我不确定如何解决这个问题/我误解了什么。
Mapping
在密钥中是不变(记录于here)。这意味着 Mapping[T1, str]
是 (<:
) Mapping[T2, str]
的子类型当且仅当 T1
和 T2
指的是同一类型,并且 T1
是 T2
的子类型没有帮助。因此,您可以仅传递 dict[Hashable, str]
或以 Hashable
作为键类型的另一个映射。
这里的解决方案是使用
Mapping[Any, str]
,而不是打扰Hashable
。这不会降低类型严格性:如果 key 不是 Hashable
,则映射将永远不会被构造,因此无法传递给函数。
def f(x: Mapping[Any, str]) -> None:
print(x)
dict_ = {'hello' : 'something'}
f(x = dict_)
您也可以显式注释以允许这样做,但是您将在传递给函数之前注释所有字典,这并不方便:
dict_: dict[Hashable, str] = {'hello' : 'something'}