FW: Strange behaviour of __del__

Tom Harris TomH at optiscan.com
Mon Dec 10 22:11:26 CET 2001


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?

Tom Harris, Software Engineer
Optiscan Imaging, 15-17 Normanby Rd, Notting Hill, Melbourne, Vic 3168,
Australia
email tomh at optiscan.com     ph +61 3 9538 3333  fax +61 3 9562 7742

This email may contain confidential information. If you have received this
email in error, please delete it immediately,and inform us of the mistake by
return email. Any form of reproduction, or further dissemination of this
email is strictly prohibited. Also, please note that opinions expressed in
this email are those of the author, and are not necessarily those of
Optiscan Pty Ltd.






More information about the Python-list mailing list