Q:

How to do something when a python object is destroyed?

How can I perform some cleanup action when a python object is destroyed (for any reason)?

A:

Extend the class of the object:
class MyClass(object):
    def __del__(self):
        object.__del__(self)
        dosomething()

