Today I learned that Python generators can return a value.
Generators are interesting Python objects that produce a series of values, but one by one. In a way, they can be thought of as stateful functions. (That is, functions with state.)
What I learned is that generators can also return something. Here is the tweet that prompted this discovery:
#Python pop quiz: Is this code valid? If so, what does it do?
— Raymond Hettinger (@raymondh) October 7, 2021
def f():
yield 10
return 20
g = f()
print(next(g))
print(next(g))
When you use a return
inside a generator,
the generator will have that returned information in its StopIteration
exception when it's done:
>>> def f():
... yield 10
... return 20
...
>>> gen = f()
>>> next(gen)
10
>>> next(gen)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration: 20
If you want to get access to that value, you just need to catch the exception:
>>> gen = f(); next(gen);
10
>>> try:
... next(gen)
... except StopIteration as e:
... val = e.value
...
>>> val
20
That's it for now! Stay tuned and I'll see you around!
+35 chapters. +400 pages. Hundreds of examples. Over 30,000 readers!
My book “Pydon'ts” teaches you how to write elegant, expressive, and Pythonic code, to help you become a better developer. >>> Download it here 🐍🚀.