[Python-ideas] Catching the return value of a generator at the end of a for loop

Stefano Borini stefano.borini at gmail.com
Tue Apr 16 16:54:31 EDT 2019


given the following code

def g():
    yield 2
    yield 3
    return 6

for x in g():
    print(x)

The output is obviously
2
3

As far as I know, there is currently no way to capture the
StopIteration value when the generator is used in a for loop. Is it
true?
If not, would a syntax like:

for x in g() return v:
    print(x)

print(v) # prints 6

be useful? It would be syntactic sugar for (corner cases omitted)

def g():
    yield 2
    yield 3
    return 6

it = iter(g())
while True:
    try:
        x = next(it)
    except StopIteration as exc:
        v = exc.value
        break
    else:
        print(x)
print(v)

-- 
Kind regards,

Stefano Borini


More information about the Python-ideas mailing list