For more information on topics covered in this lesson, check out these resources:
Using return vs yield in Generator Functions
In this lesson, we’ll explore what happens when you use a
return statement in a generator function. A generator function is a function that produces a sequence of values.
This is done by using
yield statements inside the function. A call to this function returned something referred to as a generator iterator.
00:22 So this type of function is something like a factory, not to be confused with the factory pattern we saw earlier. So we can think of this as a generator factory.
You can see the Real Python resources How to Use Generators and
yield in Python and Python Generators 101 for more information on generator functions.
You can use
return statements in generator functions to indicate that there is no more work for the function to do. When this happens during program execution, the function raises a
StopIteration exception when it encounters a
The return value from the function will be used as the exception’s initializer argument and will be stored in its
.value attribute. Here’s a simple generator that will produce
2 as requested, and then return
3 when finished To use it, we assign the function call to a variable, which becomes our generator object.
Then we use the function
next() with our generator as an argument to retrieve the next item from that generator. After using all of the items the generator will produce, another call to
next() raises the
StopIteration exception—in this case, with the return value of
3. We can actually see this happen.
01:58 Let’s create our generator.
Usually, there’s a more complicated process to produce a sequence of values from the
yield statements, but here we’re more interested in the effect of the
02:17 Now we’ll assign the function call to a variable,
generator object. Now we’ll attempt to produce some values from it.
next(g) gives us
The next time we call it, we get the
2. One more time.
Since there’s nothing left, we get the
StopIteration exception, and we can see that its
.value is the return value
So as you saw, we use the generator to produce the values
2 on demand. We did that by using Python’s built-in function
next(), which retrieves the next item from a Python generator.
The first two calls to
next() produce the values
2 from the
yield statements in the function. With a third call to
next(), we had used up all of the values the generator was prepared to provide, so a
StopIteration exception was raised. Finally, you were able to see the use of a
return statement in a generator function.
In this case, the return value
3 became the value of the exception’s
.value attribute. Next, we’ll summarize everything you learned in this course.
Become a Member to join the conversation.