【问题标题】:Combining mypy Union and nested TypedDict causes mypy errror: incompatible return value结合 mypy Union 和嵌套的 TypedDict 导致 mypy 错误:返回值不兼容
【发布时间】:2020-03-03 12:34:28
【问题描述】:

我想将TypedDictUnion 结合使用。这样一个函数就可以返回AB。 Mypy 能够直接正确检测TypedDict 返回类型。但是当TypedDict 嵌套在Union 中时,它就不起作用了。

from typing_extensions import TypedDict
from typing import Union


class A(TypedDict):
    a: str


class B(TypedDict):
    b: str


def works() -> A:
    return {'a': 'value'}
    # Works as expected


def problem() -> Union[A, B]:
    return {'a': 'value'}
    # mypy_error: Incompatible return value type (got "Dict[str, str]", expected "Union[A, B]")
    # Reports an error while it should be valid


def workaround() -> Union[A, B]:
    x: A = {'a': 'value'}

    return x
    # This works again but is not very elegant

一种可能的解决方法是分配给临时返回的类型提示变量(请参阅workaround())。有没有更优雅的方式来做到这一点?

注意:Python 3.7

【问题讨论】:

    标签: python python-3.x union mypy


    【解决方案1】:

    引用PEP 589:

    通常需要显式的 [TypedDict] 类型注释,否则类型检查器可能会假定普通字典类型,以实现向后兼容性。当类型检查器可以推断出构造的字典对象应该是 TypedDict 时,可以省略显式注释。

    因此,在代码中明确定义类型并没有错。另一种可能性是直接“实例化”A

    def problem() -> Union[A, B]:
        return A(a='value')
    

    虽然这当然只是一个语法糖,在运行时会被dict 替换。

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 2017-10-14
      • 2020-06-10
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 2023-02-23
      • 1970-01-01
      • 2017-10-10
      相关资源
      最近更新 更多