组合mypy联合和嵌套TypedAct会导致mypy错误:返回值不兼容

2024-04-29 19:02:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把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


Tags: fromimporttyping类型returnvaluedeferror
1条回答
网友
1楼 · 发布于 2024-04-29 19:02:55

来自PEP 589的引文:

An explicit [TypedDict] type annotation is generally needed, as otherwise an ordinary dictionary type could be assumed by a type checker, for backwards compatibility. When a type checker can infer that a constructed dictionary object should be a TypedDict, an explicit annotation can be omitted.

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

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

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

相关问题 更多 >