typing.Generator 从生成器中提取 ReturnType
typing.Generator extract ReturnType from Generator
从官方 Python docs:
获取这个正确输入的示例
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
值保持为生成器类型,因为代码对该值不做任何操作,因此被 return 编辑为 Generator[int, float, str]
类型。这会导致错误,因为 use_generator()
期望 return val
作为 str
类型。
从官方 Python docs:
获取这个正确输入的示例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
值保持为生成器类型,因为代码对该值不做任何操作,因此被 return 编辑为 Generator[int, float, str]
类型。这会导致错误,因为 use_generator()
期望 return val
作为 str
类型。