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

Stephan Sahm Stephan.Sahm at gmx.de
Fri Oct 3 09:36:47 CEST 2014


Thank you very much Chris!

works like a charm. I already know a bit about generator, but I haven't
thought that such is also possible. Impressively powerful language

best,
Stephan

On 3 October 2014 09:01, Chris Angelico <rosuav at gmail.com> wrote:

> 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
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20141003/3d799fe2/attachment.html>


More information about the Python-ideas mailing list