Bug in Python 1.5.2 exception handling?

Tim Peters tim_one at email.msn.com
Wed Dec 15 01:08:55 EST 1999


[Dave Cole]
> It looks like function locals are not deleted if that function is
> terminated by an exception.

That's true, but it's not a bug:  Python doesn't define the lifetime of
objects.  CPython is much more predictable than JPython in this respect--
thanks to using refcounts --but you still rely on it at your own risk.  In
the case of a function that terminates due to exception, the locals are
still very much alive, because they *can* be reached via the traceback
object (from which the chain of stack frames can be reached, from which the
locals can be reached).

> They seem to hang around until they are unref'ed when the function
> is next called.

That one is an illusion.  Your function happened always to raise an
exception, and the act of raising an exception causes the previous traceback
object to become unreachable (and so also the old chain of stack frames, and
so also their locals).

Change your loop to:

for val in range(3):
    try:
        check_raise(val)
    except:
        try:
            raise "dummy"
        except:
            pass

and you'll see that the 'raise "dummy"' has the same effect.


> class c:
>     def __init__(self, val):
>         self.val = val
>     def __del__(self):
>         print val, 'deleted'

You really want

        print self.val, 'deleted'

there.  As is, it's picking up the global name "val", which is at best
accidentally related to the val passed to __init__.  This accounts for the
"repeated" deletion of object 2 at the end of your msg:

> raise: 2 deleted
> 2 deleted

if-only-illusions-cancelled-out<wink>-ly y'rs  - tim






More information about the Python-list mailing list