Dynamically change __del__

Nikolaus Rath Nikolaus at rath.org
Fri Apr 30 21:16:02 CEST 2010


Hi,

I'm trying to be very clever:

class tst(object):
    def destroy(self):
        print 'Cleaning up.'
        self.__del__ = lambda: None
    def __del__(self):
        raise RuntimeError('Instance destroyed without running destroy! Hell may break loose!')
        
However, it doesn't work:

In [2]: t = tst()

In [3]: t = None
Exception RuntimeError: RuntimeError('Instance destroyed without running destroy! Hell may break loose!',) in <bound method tst.__del__ of <__main__.tst object at 0x978566c>> ignored

In [4]: t = tst()

In [5]: t.destroy()
Cleaning up.

In [6]: t = None
Exception RuntimeError: RuntimeError('Instance destroyed without running destroy! Hell may break loose!',) in <bound method tst.__del__ of <__main__.tst object at 0x978566c>> ignored

$ python -V
Python 2.6.4


Apparently Python calls the class attribute __del__ rather than the
instance's __del__ attribute. Is that a bug or a feature? Is there any
way to implement the desired functionality without introducing an
additional destroy_has_been_called attribute?


(I know that invocation of __del__ is unreliable, this is just an
additional safeguard to increase the likelihood of bugs to get noticed).



Best,

   -Nikolaus

-- 
 »Time flies like an arrow, fruit flies like a Banana.«

  PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C



More information about the Python-list mailing list