【问题标题】:Is there any guarantee that this will be a Generator?是否可以保证这将是一个生成器?
【发布时间】:2019-12-15 03:21:41
【问题描述】:
def city_generator():
    print("city gen called")
    return 1  # <--- over simplified to drive the point of the question
    yield "amsterdam"
    yield "los angeles"

>>> citygenobj = city_generator()
>>> print(citygenobj)
<generator object city_generator at 0x02CE73B0>
>>> next(citygenobj)
city gen called
Traceback (most recent call last):
  File "<pyshell#137>", line 1, in <module>
    next(citygenobj)
StopIteration: 1

问题:这个函数是否作为生成器是否依赖于 python 实现?或者python语言规范是否保证如果你有一个yield语句,不管yield是否可达,它都是一个生成器?

【问题讨论】:

  • 内部yield的存在将使它成为一个生成器。代码或控制流是否可以到达任何 yield 语句在该决定中并不重要。 yield 语句可以在一个永远不会被命中的 if 语句中。

标签: python python-3.x generator yield


【解决方案1】:

是的,如果您在函数中包含 yield,则该函数将成为生成器(如果无法访问 yield 也没关系)。

来自documentation

Yield 表达式和语句仅在定义一个 生成器函数,并且仅在生成器主体中使用 功能。在函数定义中使用 yield 足以导致 该定义用于创建生成器函数而不是普通函数 功能。

【讨论】:

    猜你喜欢
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    相关资源
    最近更新 更多