使用映射键入函数,可用,以便它接受python mypy的字典

发布于 2025-02-13 00:51:23 字数 822 浏览 0 评论 0 原文

我正在尝试键入一个可以变化的字典 - 并认为映射,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

当我浏览各个部分时 - 它们似乎都还可以,所以我不确定如何解决这个问题 /我误解了什么。

I'm trying to typehint a dictionary which can vary - and thought that Mapping, Hashable would work as follows:

from typing import Hashable, Mapping

def f(x : Mapping[Hashable, str]) -> None:
    print(x)
    

_dict = {'hello' : 'something'}

f(x = _dict)

errors with:

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)

I don't understand the reason for this error though, I've passed it a dictionary which is a "Mapping" type ? (https://mypy.readthedocs.io/en/stable/builtin_types.html). And the keys are hashable, which I thought would be a type of Hashable.

When I go through the parts - they all seem ok, so I'm not sure how to solve this / what I've misunderstood.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

殤城〤 2025-02-20 00:51:23

映射不变(记录在此处)。这意味着映射[T1,str] 是(<:)的子类型)映射[T2,str] i时,仅当代码> t1 和 t2 请参阅同一类型, t1 t2 的子类型无济于事。因此,您只能将 dict [hashable,str] 或其他用 hashable 作为密钥类型传递。

这里的解决方案是,不打扰使用 Hashable 。这不会降低类型的严格性:如果密钥不是 hashable ,则将永远不会构造映射,因此不能将其传递给函数。

def f(x: Mapping[Any, str]) -> None:
    print(x)


dict_ = {'hello' : 'something'}
f(x = dict_)

您还可以明确注释以允许此注释,但是随后您会在传递到功能之前注释所有词典,这并不方便:

dict_: dict[Hashable, str] = {'hello' : 'something'}

Mapping is invariant (documented here) in key. It means that Mapping[T1, str] is a subtype of (<:) Mapping[T2, str] if and only if T1 and T2 refer to the same type, and T1 being subtype of T2 does not help. So you can pass only dict[Hashable, str] or another mapping with Hashable as key type.

The solution here is to use Mapping[Any, str] and not bother with Hashable. This does not reduce type strictness: if key is not Hashable, then the mapping will never be constructed and thus cannot be passed to function.

def f(x: Mapping[Any, str]) -> None:
    print(x)


dict_ = {'hello' : 'something'}
f(x = dict_)

You can also annotate explicitly to allow this, but then you'll annotate all dictionaries before passing to function, and this is not convenient:

dict_: dict[Hashable, str] = {'hello' : 'something'}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文