Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Question: Is it dependent on a python implementation whether this function acts as a generator or not ? Or does the python language spec guarantee that if you have a yield statement, it is a generator regardless of whether the yield is reachable or not ?

like image 395
2020 Avatar asked Dec 27 '25 14:12

2020


1 Answers

Yes, if you have yield inside a function, the function will become a generator (doesn't matter if the yield couldn't be reached).

From the 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.

like image 111
Andrej Kesely Avatar answered Dec 30 '25 03:12

Andrej Kesely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!