使用 Mapping、Hashable 键入函数,以便它接受带有 python Mypy 的字典

问题描述 投票:0回答:1

我正在尝试输入一本可能会有所不同的字典 - 并认为

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

当我浏览这些部分时 - 它们看起来都不错,所以我不确定如何解决这个问题/我误解了什么。

python mypy python-typing
1个回答
2
投票

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'}
© www.soinside.com 2019 - 2024. All rights reserved.