【问题标题】:What type signature do generators have in Python?Python 中的生成器有哪些类型签名?
【发布时间】:2016-02-28 08:24:25
【问题描述】:

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

def yieldMoreIfA(text:str):
    if text == "A":
        yield text
        yield text
        return
    else:
        yield text
        return

正确的签名是什么?

【问题讨论】:

    标签: python python-3.x annotations type-hinting


    【解决方案1】:

    有一个Generator[yield_type, send_type, return_type] 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
    

    【讨论】:

    • 什么是send_type和return_type?
    • @Drew:您可以使用generator.send() 将值发送到生成器。 send_type 指定这些值的类型。在 Python 3.3 及更高版本中,当生成器使用 return some_expression 时,返回值被包装在 StopIteration 异常中,并成为 yield from 表达式的返回值(当 delegating to a subgenerator 时,请参阅 yield from); return_type 参数指定这将产生什么类型。
    猜你喜欢
    • 2016-03-18
    • 2021-11-14
    • 2018-09-23
    • 1970-01-01
    • 2012-12-26
    • 2011-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多