[英]Combining mypy Union and nested TypedDict causes mypy errror: incompatible return value
我想将TypedDict
与Union
结合起来。 这样一个函数就可以返回A
或B
。 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
引用自PEP 589 :
通常需要显式的 [TypedDict] 类型注释,否则类型检查器可以假设普通字典类型,以实现向后兼容。 当类型检查器可以推断构造的字典对象应该是 TypedDict 时,可以省略显式注释。
因此,在代码中明确定义类型并没有错。 另一种可能性是直接“实例化” A
:
def problem() -> Union[A, B]:
return A(a='value')
虽然这当然只是一个语法糖,在运行时会被dict
替换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.