generators and exceptions

Clark C. Evans cce at clarkevans.com
Tue Mar 18 06:19:26 CET 2003


Andrew Bennetts wrote:
> 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 i
> your generator calls?

Andrew, thanks for opening my eyes to the complexities involved; 
for now I can just 'yield' my Exception.   More generally, I was
using generators for a 'light-weight' thread solution, but the 
problem was that exceptions would unwind the stack on me...

On Tue, Mar 18, 2003 at 03:30:43PM +1200, Greg Ewing:
| It seems to me that what Mr. Evans wants is some way for
| a generator to cause an exception to be raised in its
| caller, without having to propagate the exception up
| through its own stack frame first.
| 
| Suppose there were a hypothetical "yield raise" statement
| which did this, then he could write
| 
|   def mygen(val):
|     while val > 0:
|       if val % 2:
|         yield raise MyExc
|       else:
|         yield val
|       val -= 1

Yes; I guess more generally I'm just looking for a way
to raise an exception all the way back though N levels
of generators in such a way that I can 'resume' the 
entire 'light-weight thread' once the issue is resolved.

| The "yield raise" statement wouldn't disturb the control
| flow of the generator at all -- it would be just like a
| normal yield, except that whatever called the generator-
| iterator's next() would get an exception instead of a
| return value.

Right, only that it'd do a "yield raise" in subordinate
generators as well, so that the entire stack could be
resumed.   I'm just intrigued as to how close generators
work as light weight threads... the error handling is
pretty much the primary thing lacking...

| As for how *useful* such a thing would be, I don't know.
| I won't be leaping up to write a PEP, though...

*grins*  thanks Greg.

Clark





More information about the Python-list mailing list