[Python-Dev] Combining the best of PEP 288 and PEP 325: generatorexceptions and cleanup

Raymond Hettinger python at rcn.com
Wed May 18 19:24:29 CEST 2005


> I'd like to propose to make that a separate PEP, which can combine
> elements of PEP 288 and PEP 325. 

+1 
Overall, the combined PEP proposal looks pretty good.



> - g.throw(type, value, traceback) causes the specified exception to be
> thrown at the place where the generator g is currently suspended.

Are the value and traceback arguments optional as they are with the
current raise statement?  If they are optional, what would the default
be?  I think the preferred choice is to have the call to the throw
method be the anchor point.  That makes sense in a traceback so you can
see who threw the exception.

The alternative is to have the generator resumption point be the anchor.
That is closer to the notion that throw(ex) is equivalent to a "raise
ex" following the last yield.   This probably isn't the way to go but
the PEP should address it explicitly.



> If the generator raises another exception (this includes
> the StopIteration produced when it returns) that exception is raised
> by the throw. In summary, throw() behaves like next() except it raises
> an exception at the place of the yield.

The parallel to next() makes this easy to understand, learn, and
implement.  However, there are some disadvantages to passing through a
StopIteration.  It means that throw() calls usually need to be wrapped
in a try/except or that a generator's exception handler would terminate
with a "yield None" where a "return" would be more natural.  As a
example, it is a bit painful to simulate the effects of g.close() using
g.throw(GeneratorExit).




> That's it! With this, we can write the decorator from Nick's PEP 3XX
> and the generator examples in PEP 343 can be rewritten to have a
> try/finally clause around the yield statement.

Yea!  This is very nice.


 
> Oh, somewhere it should be stated that yield without an expression is
> equivalent to yield None. PEP 342 ("continue EXPR") already implies
> that, so we don't have to write a separate PEP for it.

Right.



> I also propose
> to go with the alternative in PEP 342 of using next() rather than
> __next__() -- generators will have methods next(), throw(), and
> close().

+0  The switch from __next__() to next() is attractive but not essential
to the proposal.  Besides a small cost to backwards compatability, it
introduces yet another new/old style distinction where we have to keep
both forms in perpetuity.



Raymond


More information about the Python-Dev mailing list