generators and exceptions

Andrew Bennetts andrew-pythonlist at puzzling.org
Mon Mar 17 07:13:10 EST 2003


On Mon, Mar 17, 2003 at 07:27:55AM +0000, Clark C. Evans wrote:
> Thank you for responding Tim, as you expected my question is less
> about what generator behavior is, as it is about what generator
> behavior with regard to exceptions could be.
> 
> On Sat, Mar 15, 2003 at 11:20:46PM -0500, Tim Peters wrote:
> | >     from __future__ import generators
> | >     class MyExc(Exception): pass
> | >     def mygen(val):
> | >         while val > 0:
> | >            if val % 2: raise MyExc
> | >            yield val
> 
>                val -= 1
> 
> | Read the PEP and your expectations will change <wink>.  The code exactly as
> | you gave should obviously produce only 4 (val is set to -1 and so the loop
> | exits).  With the suggested guess at what was intended, it should still
> | produce only 4, but due to raising an exception within the generator when
> | val is 3 (instead of falling off the end because val is -1).
> 
> Right.  I did, but this still didn't stop my expectations.  I was wishing 
> that I could resume the generator after the exception was thrown.

But from which would you expect it to resume?  Just before the exception was
raised?  Just after?  What about try/except blocks?  What if the exception
was raised inside a function called by a generator?  What about an exception
thrown by a generator that your generator calls?

I can't see any useful answers to these that make sense, unless exceptions
behave exactly as they do now.

-Andrew.






More information about the Python-list mailing list