【问题标题】:What is the return type hint of a generator function? [duplicate]生成器函数的返回类型提示是什么? [复制]
【发布时间】:2017-09-25 07:41:43
【问题描述】:

我正在尝试为生成器函数编写:rtype: 类型提示。它返回的类型是什么?

例如,假设我有这个产生字符串的函数:

def read_text_file(fn):
    """
    Yields the lines of the text file one by one.
    :param fn: Path of text file to read.
    :type fn: str
    :rtype: ???????????????? <======================= what goes here?
    """
    with open(fn, 'rt') as text_file:
        for line in text_file:
            yield line

返回类型不仅仅是一个字符串,它是某种可迭代的字符串?所以我不能只写:rtype: str。正确的提示是什么?

【问题讨论】:

  • 返回带有字符串的生成器
  • 看起来你不是要求类型提示,而是 :rtype: 的文档字符串插入
  • 人们甚至没有阅读问题就标记为重复。叹息……
  • @Wood 再看一遍...
  • @Jean-FrançoisCorbett 另一个问题要求类型注释。这个请求为:rtype: 插入文档字符串。它们是不同的东西。

标签: python python-2.7 generator yield type-hinting


【解决方案1】:

Generator

Generator[str, None, None]Iterator[str]

【讨论】:

  • 既然 Python 3.9 支持更复杂的类型提示,有没有新的答案?
【解决方案2】:

注释生成器的泛型类型是Generator[yield_type, send_type, return_type],由typing 模块提供:

def echo_round() -> Generator[int, float, str]:
    res = yield
    while res:
        res = yield round(res)
    return 'OK'

您也可以使用Iterable[YieldType]Iterator[YieldType]

【讨论】:

  • 有人能解释一下echo_round这个函数的作用吗?我迷路了!
  • @TimokKhan 第一个yield,没有值,将None返回给调用者,并将其分配给res。如果再次调用,调用者会得到一个StopIteration 异常。但是,如果调用者向生成器发送了一个值,则将其分配给res,并在四舍五入后生成。 res 再次变为 None。只要用户发送输入,生成器就会不断生成舍入值;它会在没有输入的情况下立即停止。见replit.com/@socialguy/generator#main.py
  • 谢谢!了解它的使用方式很有帮助!
猜你喜欢
  • 2018-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-13
  • 1970-01-01
  • 2012-03-14
  • 1970-01-01
  • 2016-02-25
相关资源
最近更新 更多