FW: Strange behaviour of __del__

Peter Wang pzw1 at hotmail.com
Mon Dec 10 22:06:42 EST 2001


hi tom,

the __del__ method is only called when the reference count of an
object reaches 0.  in your example, "a" is actually still referenced
when you reach the interpreter prompt after the exception is thrown,
because the traceback object contains the stack frame, which in turn
references "a".  (check out
http://www.python.org/doc/current/ref/customization.html, read the
bold "Programmer's Note")  so, when you manually execute "del a", that
decreases the refcount to 0 and that in turn causes "a" to be deleted.

the NameError exception after that is confusing, i don't know why it's
doing that.  probably the destructor itself throwing an exception.

-peter


Tom Harris <TomH at optiscan.com> wrote in message news:<mailman.1008018734.10343.python-list at python.org>...
> Greetings,
> 
> Playing around with the __del__ method of classes led me to this odd
> observation:
> 
> <<in file Script1.py>>
> class A:
>     def __init__(self, a):
>         if a:
>             raise RuntimeError
> 
>     def __del__(self):
>         print 'In __del__()...'
> 
> import Script1
> >>> a = Script1.A(1)
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
>   File "Script1.py", line 4, in __init__
>     raise RuntimeError
> RuntimeError
> >>> del a
> In __del__()...
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
> NameError: name 'a' is not defined
> >>>        
> 
> Why is the __del__ method being called? Note that Python raised a NameError.
> If 'a' is not defined, how does Python find, let alone call a method on it.
> Am I expectiong Python to be like C++ where a class instance is not
> constructed until it falls off the last brace of the constructor?



More information about the Python-list mailing list