In Python, the return statement inside a generator is not used to return a value in the conventional sense that return is used in regular functions. Instead, when a return statement is executed in a generator, it signals that the generator is done and should raise a StopIteration exception. If a value is provided with the return statement in a generator, that value is attached to the StopIteration exception as its value attribute.
You would not see this value in a for loop, because for loops are designed to handle StopIteration exceptions by terminating the iteration without reporting the value. However, you can access this value if you're manually iterating the generator using the next() function. This is how you might do it:
def my_generator():
yield 1
yield 2
return "No more elements"
gen = my_generator()
while True:
try:
# Get the next item from the generator
item = next(gen)
print(item)
except StopIteration as e:
# Catch the StopIteration exception and print the returned value
print('Generator returned:', e.value)
break
Output:
1
2
Generator returned: No more elements
The returned value might be used for purposes such as:
-
Signaling why the generator is finished: The value can indicate that iteration has stopped due to some condition being met instead of simply running out of items to yield.
-
Returning a summary or some result: After an iteration over a series of items, you might want to return some kind of summary or result that isn't part of the normal items being yielded.
-
Communicating status or a final state: The value can communicate a status code, an error message, or the final state of a computation.
-
If the generator is also a coroutine, the return value can be used in asynchronous code to signal completion and return an additional result when awaited.
Here's an example using PEP 479, which makes returning a value from a generator used for more pythonic error handling:
def divide(values, divisor):
for value in values:
if divisor == 0:
return "Cannot divide by zero"
yield value / divisor
result = divide([1, 2, 3, 4, 5], 0)
try:
while True:
print(next(result))
except StopIteration as e:
print(e.value) # Prints: Cannot divide by zero
It's worth noting that returning values from generators is a somewhat advanced feature and not commonly seen. The use of return in this way became possible in Python 3.3 and is carefully designed to only influence the behavior when the generator is exhausted, without affecting standard loop semantics.