[Python-Dev] Generator cleanup idea (patch: try/finally in generators)

Greg Ewing greg@cosc.canterbury.ac.nz
Tue, 30 Jul 2002 13:12:19 +1200 (NZST)


> but it would have been a great surprise then that the finally clause
> may never get executed at all.  Better to outlaw it than that (or, as
> the PEP says, that would be "too much a violation of finally's purpose
> to bear").

I don't think you'd really be breaking any promises.
After all, if someone wrote

  def asdf():
    try:
      something_that_never_returns()
    finally:
      ...

they wouldn't have much ground for complaint that the
finally never got executed. The case we're talking about
seems much the same situation.

> When I've needed resource-cleanup in a generator, I've made the generator a
> method of a class, and put the resources in instance variables.  Then
> they're easy to clean up at will (even via a __del__ method, if need
> be;

I take it you usually provide a method for explicit cleanup.
How about giving generator-iterators one, then, called
maybe close() or abort(). The effect would be to raise
an appropriate exception at the point of the yield,
triggering any except or finally blocks.

This method could even be added to the general iterator
protocol (implementing it would be optional). It would
then provide a standard name for people to use for
cleanup methods in their own iterator classes.

Greg Ewing, Computer Science Dept, +--------------------------------------+
University of Canterbury,	   | A citizen of NewZealandCorp, a	  |
Christchurch, New Zealand	   | wholly-owned subsidiary of USA Inc.  |
greg@cosc.canterbury.ac.nz	   +--------------------------------------+