FW: Strange behaviour of __del__

Duncan Booth duncan at NOSPAMrcp.co.uk
Tue Dec 11 04:34:32 EST 2001

David Bolen <db3l at fitlinxx.com> wrote in 
news:u7kru70s6.fsf at ctwd0143.fitlinxx.com:

> I'm not sure of precisely when the traceback is cleared (and it seems
> to be somewhat Python version specific), but for example, the same
> thing can happen even if the next command isn't del:

The del command throws an exception (because there is no a). The traceback 
for the previous exception is held until the next exception is thrown, when 
it is replaced by the traceback information for the new exception.

The class object continues to exist until the stack frame that references 
it is destroyed. Since the only stack frame with a reference to the object 
is the __init__, you can make sure the __del__ is called earlier by 
deleting self before raising the exception:

class A:
    def __init__(self, a):
        if a:
            del self
            raise RuntimeError

    def __del__(self):
        print 'In __del__()...'

and now:
>>> a = script1.A(1)
In __del__()...
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in ?
    a = script1.A(1)
  File "D:\Python21\script1.py", line 5, in __init__
    raise RuntimeError
>>> del a
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in ?
    del a
NameError: name 'a' is not defined

which is perhaps less confusing.

Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?

More information about the Python-list mailing list