[Python-ideas] possible extension to how the new StopIteration is handled (python >=3.3)

Chris Angelico rosuav at gmail.com
Fri Oct 3 09:01:59 CEST 2014


On Fri, Oct 3, 2014 at 4:36 PM, Stephan Sahm <Stephan.Sahm at gmx.de> wrote:
> Thank you both very much,
>
> I see that this longevity problem is really crucial. A pity for me ;)
> best wishes,
> Stephan

In the general case, it is. But if you want it just for your own
generators, it ought to be possible to write a decorator that
yields-from your original function, retains the return value, and then
reraises the exception repeatedly. Here's a simple version:

def gen():
    yield 0
    return 1
class repeater:
    def __init__(self):
        self.g=gen()
    def __iter__(self): return self
    def __next__(self):
        if hasattr(self, "done"): raise StopIteration(self.done)
        try:
            return next(self.g)
        except StopIteration as exc:
            self.done=exc.value
            raise

Generalizing this is left as an exercise for the reader.

ChrisA


More information about the Python-ideas mailing list