生成器在Python中使用什么类型的签名?

Chr*_*ian 8 python annotations type-hinting python-3.x

鉴于新的Python 3.5允许使用类型签名进行类型提示,我想使用新功能,但我不知道如何使用以下结构完全注释函数:

def yieldMoreIfA(text:str):
    if text == "A":
        yield text
        yield text
        return
    else:
        yield text
        return
Run Code Online (Sandbox Code Playgroud)

什么是正确的签名?

Mar*_*ers 9

有一种Generator[yield_type, send_type, return_type]类型:

from typing import Generator

def yieldMoreIfA(text: str) -> Generator[str, None, None]:
    if text == "A":
        yield text
        yield text
        return
    else:
        yield text
        return
Run Code Online (Sandbox Code Playgroud)

  • 什么是send_type和return_type? (2认同)
  • @Drew:您可以使用`generator.send()`将值发送到生成器.`send_type`指定这些值的类型.在Python 3.3及更高版本中,当一个生成器使用`return some_expression`时,返回的值被包装在`StopIteration`异常中,并成为`yield from`表达式的返回值(当[委托给子生成器时](https:/ /docs.python.org/3/whatsnew/3.3.html#pep-380-syntax-for-delegating-to-a-subgenerator),参见[`yield from`](https://docs.python.org/ 3 /参考/ expressions.html#收率表达式)); `return_type`参数指定这将产生的类型. (2认同)