【发布时间】:2020-03-03 12:34:28
【问题描述】:
我想将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
【问题讨论】:
标签: python python-3.x union mypy