0

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?

pepoluan
  • 6,132
  • 4
  • 46
  • 76
  • 2
    The generator doesn't seem to generate anything, so maybe the better solution would be to not use a generator? – mkrieger1 Nov 16 '22 at 14:31
  • A context manager would probably be better. Its `__enter__` method can return the thing that will accumulate stuff, then you can access the accumulator from the `__exit__` method or the thing returned by `__enter__` (or any time after the `__exit__` method is called). – chepner Nov 16 '22 at 14:33
  • Perhaps you should have a class that contains the generator function as a member. Then you could just call a different function on that object. – Mark Ransom Nov 16 '22 at 14:34

0 Answers0