是否可以保证这将是一个生成器?

inq*_*One 3 python yield generator python-3.x

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
Run Code Online (Sandbox Code Playgroud)

问题:此函数是否充当生成器是否取决于python实现?还是python语言规范保证如果您有一条yield语句,则无论生成器是否yield可达,它都是生成器?

And*_*ely 5

是的,如果您yield在函数内部,则该函数将成为生成器(如果yield无法达到,则无关紧要)。

从文档中:

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