[Python-Dev] patch: try/finally in generators
Guido van Rossum
guido@python.org
Mon, 29 Jul 2002 16:21:07 -0400
> Yeah, I know. I'm not too proud of it but I was looking for instant
> gratification...
The search for instant gratification probably ties a lot of the Python
community together...
> > 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.
But __del__ is in essence asynchronous. On the other hand,
try/finally is traditionally completely synchronous. Adding a case
where a finally clause can execute asynchronously (or not at all,
if there is a global ref or cyclical garbage keeping the generator
alive) sounds like a breach of promise almost.
> > 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.
But you still have to be careful with how you incref/decref -- see my
fatal error report in debug mode.
--Guido van Rossum (home page: http://www.python.org/~guido/)