使用映射键入函数,可用,以便它接受python mypy的字典
我正在尝试键入一个可以变化的字典 - 并认为映射,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/readthedocs.io/en/en/en/en/stable/stable/builtin_types.html )。密钥是可用的,我认为这将是一种 Hashable
。
当我浏览各个部分时 - 它们似乎都还可以,所以我不确定如何解决这个问题 /我误解了什么。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
映射
是不变(记录在此处)。这意味着映射[T1,str]
是(<:
)的子类型)映射[T2,str]
i时,仅当代码> t1 和t2
请参阅同一类型,t1
是t2
的子类型无济于事。因此,您只能将dict [hashable,str]
或其他用hashable
作为密钥类型传递。这里的解决方案是,不打扰使用
Hashable
。这不会降低类型的严格性:如果密钥不是hashable
,则将永远不会构造映射,因此不能将其传递给函数。您还可以明确注释以允许此注释,但是随后您会在传递到功能之前注释所有词典,这并不方便:
Mapping
is invariant (documented here) in key. It means thatMapping[T1, str]
is a subtype of (<:
)Mapping[T2, str]
if and only ifT1
andT2
refer to the same type, andT1
being subtype ofT2
does not help. So you can pass onlydict[Hashable, str]
or another mapping withHashable
as key type.The solution here is to use
Mapping[Any, str]
and not bother withHashable
. This does not reduce type strictness: if key is notHashable
, then the mapping will never be constructed and thus cannot be passed to function.You can also annotate explicitly to allow this, but then you'll annotate all dictionaries before passing to function, and this is not convenient: