gpt4 book ai didi

python - 为什么 TypedDict 与匹配的 Mapping 不兼容?

转载 作者:行者123 更新时间:2023-12-04 01:33:41 26 4
gpt4 key购买 nike

考虑以下代码:

from typing import Any, Mapping, TypedDict


class MyDict(TypedDict):
foo: bool


def my_func_any(a: Mapping[str, Any]) -> None:
print(a)


def my_func_bool(a: Mapping[str, bool]) -> None:
print(a)


d: MyDict = {
'foo': True
}

my_func_any(d)
my_func_bool(d) # line 21

使用 mypy==0.761 检查时会出现以下错误:

test.py:21: error: Argument 1 to "my_func_bool" has incompatible type "MyDict"; expected "Mapping[str, bool]"



我希望两者都是 my_func_any(d)my_func_bool(d)没关系,但后者是一个错误。这是一个错误还是我错过了什么?

最佳答案

引用 PEP 589 :

Type Consistency

First, any TypedDict type is consistent with Mapping[str, object].

[...]

  • A TypedDict with all int values is not consistent with Mapping[str, int], since there may be additional non-int values not visible through the type, due to structural subtyping. These can be accessed using the values() and items() methods in Mapping, for example. Example:

    class A(TypedDict):
    x: int

    class B(TypedDict):
    x: int
    y: str

    def sum_values(m: Mapping[str, int]) -> int:
    n = 0
    for v in m.values():
    n += v # Runtime error
    return n

    def f(a: A) -> None:
    sum_values(a) # Error: 'A' incompatible with Mapping[str, int]

    b: B = {'x': 0, 'y': 'foo'}
    f(b)

关于python - 为什么 TypedDict 与匹配的 Mapping 不兼容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60304154/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com