def echo_round() -> Generator[int, float, str]:
sent = yield 0
while sent >= 0:
sent = yield round(sent)
return 'Done'
如何“提取”ReturnType?考虑以下示例:
def use_generator() -> str:
# Do generator stuff, keeping this a minimal example...
next(echo_round())
# Finally get the return value
val = echo_round()
# Do something else?
return val
我收到的最后一行的 mypy 错误消息:
Incompatible return value type (got "Generator[int, float, str]", expected "str")
val
变量从echo_round()
接收生成器对象。 val
值保持生成器类型,因为代码对该值不执行任何操作,因此以 Generator[int, float, str]
类型返回。这会导致错误,因为 use_generator()
期望以 val
类型返回 str
。