【问题标题】:Why is TypedDict not compatible with matching Mapping?为什么 TypedDict 与匹配 Mapping 不兼容?
【发布时间】:2020-02-19 15:47:11
【问题描述】:

考虑以下代码:

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) 都可以,但后者是一个错误。这是一个错误还是我错过了什么?

【问题讨论】:

    标签: python python-3.x mypy


    【解决方案1】:

    引用PEP 589

    类型一致性

    首先,任何TypedDict类型都与Mapping[str, object]一致。

    [...]

    • 具有所有int 值的TypedDictMapping[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 也应该始终是有效的Mapping[str, int]
    猜你喜欢
    • 2013-10-21
    • 2017-10-08
    • 2014-11-06
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    • 2021-05-06
    • 2021-04-04
    • 2012-10-14
    相关资源
    最近更新 更多