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

Is there any guarantee that this will be a Generator?

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 也没关系)。

来自documentation

Yield expressions and statements are only used when defining a generator function, and are only used in the body of the generator function. Using yield in a function definition is sufficient to cause that definition to create a generator function instead of a normal function.