打字。生成器从生成器中提取 ReturnType

问题描述 投票:0回答:1

从官方Python文档中获取这个正确输入的示例

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")
python python-typing mypy
1个回答
2
投票

val
变量从
echo_round()
接收生成器对象。
val
值保持生成器类型,因为代码对该值不执行任何操作,因此以
Generator[int, float, str]
类型返回。这会导致错误,因为
use_generator()
期望以
val
类型返回
str

© www.soinside.com 2019 - 2024. All rights reserved.