Best way to receive the ‘return’ value from a python generator

You can think of the value attribute of StopIteration (and arguably StopIteration itself) as implementation details, not designed to be used in “normal” code.

Have a look at PEP 380 that specifies the yield from feature of Python 3.3: It discusses that some alternatives of using StopIteration to carry the return value where considered.

Since you are not supposed to get the return value in an ordinary for loop, there is no syntax for it. The same way as you are not supposed to catch the StopIteration explicitly.

A nice solution for your situation would be a small utility class (might be useful enough for the standard library):

class Generator:
    def __init__(self, gen):
        self.gen = gen

    def __iter__(self):
        self.value = yield from self.gen

This wraps any generator and catches its return value to be inspected later:

>>> def test():
...     yield 1
...     return 2
...
>>> gen = Generator(test())
>>> for i in gen:
...    print(i)
...
1
>>> print(gen.value)
2

Leave a Comment