Python 为什么TypedDict与匹配映射不兼容?

Python 为什么TypedDict与匹配映射不兼容?,python,python-3.x,mypy,Python,Python 3.x,Mypy,考虑以下代码: 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':

考虑以下代码:

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:错误:“my_func_bool”的参数1具有不兼容的类型“MyDict”;应为“映射[str,bool]”

我希望
my_func_any(d)
my_func_bool(d)
都正常,但后者是一个错误。这是一个bug还是我遗漏了什么?

引用以下内容:

类型一致性 首先,任何
TypedDict
类型都与
映射[str,object]
一致

[……]

  • 带有所有
    int
    值的
    TypedDict
    Mapping[str,int]
    不一致,因为由于结构子类型,可能存在通过类型看不到的其他非int值。例如,可以使用
    Mapping
    中的
    values()
    items()
    方法访问这些属性。例如:

    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)
    

有没有办法表明
TypedDict
也应该始终是有效的
映射[str,int]