[Python-Dev] patch: try/finally in generators
Oren Tirosh
oren-py-d@hishome.net
Mon, 29 Jul 2002 23:14:26 +0300
On Mon, Jul 29, 2002 at 03:40:01PM -0400, Guido van Rossum wrote:
> > > 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.
>
> OK. Your way to find the last return statement gives me the willies
> though. :-(
Yeah, I know. I'm not too proud of it but I was looking for instant
gratification...
> Of course, since Jython has garbage collection, your finally clause
> may be executed later than you had expected it, or not at all! Are
> you sure you want this?
The same question applies to the __del__ method of any local variables
inside the suspended generator. I tend to rely on the reference counting
semantics of CPython in much of my code and I don't feel bad about it.
> There are a few other places that invoke Python code in a dealloc
> handler (__del__ invocations in classobject.c and typeobject.c). They
> do a more complicated dance with the reference count. Can you check
> that you are doing the right thing?
The __del__ method gets a reference to the object so it needs to be
revived. Generators are much simpler because the generator function does
not have any reference to the generator object.
Oren