First of all, this question is different from "Best way to receive the 'return' value from a python generator" question, because that question has a generator that does not receive values from yield
.
This question concerns a generator that actually receives values via the yield
mechanism.
So I have a code that looks kind of like this:
def gen():
...
# accumulator is defined here
...
while (incoming := (yield)) is not None:
...
# Do things with incoming
# And put in accumulator
accumulator.consume(processed_incoming)
...
return accumulator
Later on it gets invoked like so:
...
g = gen()
for item in dataset:
g.send(item)
# Exhausted the dataset, let's grab the accumulator
try:
g.send(None)
except StopIteration as si:
result = si.value
# continue our merry way
...
Is there a better way to grab the return value of gen()
besides catching the StopIteration
exception?