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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With