[Python-Dev] patch: try/finally in generators

Oren Tirosh oren-py-d@hishome.net
Mon, 29 Jul 2002 22:09:44 +0300


On Mon, Jul 29, 2002 at 01:34:01PM -0400, Guido van Rossum wrote:
> > http://www.python.org/sf/584626
> > 
> > This patch removes the limitation of not allowing yield in the try part
> > of a try/finally. The dealloc function of a generator checks if the 
> > generator is still alive and resumes it one last time from the return 
> > instruction at the end of the code, causing any try/finally blocks to be 
> > triggered. Any exceptions raised are treated just like exceptions in a
> > __del__ finalizer (printed and ignored).
> 
> I'm not sure I understand what it does.  The return instruction at the
> end of the code, if I take this literally, isn't enclosed in any
> try/finally blocks.  So how can this have the desired effect?

They're on the block stack.  The stack unwind does the rest.
 
> Have you verified that Jython can implement these semantics too?

I don't see why not. The trick of jumping to the end was just my way to
avoid adding a flag or some magic value to signal to eval_frame that it 
needs to trigger the block stack unwind on ceval.c:2201.  There must be 
many other ways to implement this.
 
> Do you *really* need this?

I'm a plumber.  I make pipelines by chaining iterators and transformations.  
My favorite fittings are generator functions and closures so I rarely need 
to actually define a class.  One of my generator functions needed to clean 
up some stuff so I naturally used a try/finally block. When the compiler 
complained I recalled that when I first read with excitement about generator 
functions there was a comment there about some arbitrary limitation of yield 
statements in try/finally blocks...  

Anyway, I ended up creating a temporary local object just so I could take 
advantage of its __del__ method for cleanup but I really didn't like it. 
After a quick look at ceval.c I realized that it would be easy to fix this 
by having the dealloc function simulate a return statement just after the 
yield that was never resumed. So I wrote a little patch to remove something 
that I consider a wart.

	Oren


  Teaser: coming soon on the dataflow library! transparent two-way 
  interoperability between iterators and unix pipes!