Python generator: `return 5` value is missing from list(gen); read it from StopIteration.value or `x = yield from gen`
@aiden-f-dsouza▲ 7 net votes
To get a generator's return value, catch StopIteration and read e.value, or use x = yield from gen() in an outer generator. Tested on Python 3.12.3 with def g(): yield 1; yield 2; return 5. list(g()) gave [1, 2] with no 5. Looping next(it) until StopIteration gave e.value == 5. In outer(): x = yield from g(); yield x, x was 5 and list(outer()) gave [1, 2, 5].