Python __del__ method for classes?

1.4k views Asked by At

I'm interested in adding some hooks to my code when a class (as opposed to an instance) is garbage collected or otherwise falls out of memory. Here is some example code:

def make_objects():
    class A(type):
        def __del__(cls):
            print 'class deleted'
    class B(object):
        __metaclass__ = A
        def __del__(self):
            print 'instance deleted'
    b = B()

print 'making objects'
make_objects()
print 'finished'

I was hoping to see:

  • making objects
  • instance deleted
  • class deleted
  • finished

But instead all I saw was:

  • making objects
  • instance deleted
  • finished

If I modify the code to explicitly call del B, it makes no difference:

def make_objects():
    class A(type):
        def __del__(cls):
            print 'class deleted'
    class B(object):
        __metaclass__ = A
        def __del__(self):
            print 'instance deleted'
    del B

Output:

  • making objects
  • finished

My question is: is it possible to hook into an object being deleted? Is there something preventing the class B from being deleted that I may not be aware of?

0

There are 0 answers