trigger a function if 'del' is called on a class instance?

Viewed 56

I really tried to get my head around this, but I simply can't think of any nice way to di this... so my question is the following:

Suppose you have an instance of a class, that has some nasty references (circular references, connected callbacks in a gui) that prevent it from being garbage-collected, but you have the possibility to "unreference" the object manually by calling x.cleanup(), e.g.:

class asdf:
    def __init__(self):
        self.a = 1    
    
    def __del__():
        # this funciton is called AFTER garbage-collection...
        print("object is destroyed")
        
    def cleanup(self):
        # a function to cleanup all references that would
        # prevent the object from being garbage-collected
        print("object is released")

x = asdf()

now if I would call

del x

the object would still remain "alive", due to the unresolved references...
however, if I do

x.cleanup()
del x

the object gets garbage-collected just fine.

Now, what I'm searching for is a possibility to automate this process, but I simply can't find a proper way to execute the cleanup-function if del is called on an instance of the class. Any help is highly appreciated!

1 Answers

This isn’t well posed: should

x=asdf()
y=x
del y

trigger it?

You might be able to make some other part of the system use weak references to break the cycles. Of course, since Python 3.4 all cycles have been collectible so long as no old-style tp_del C extensions are in use, so the issue might be overblown.

Related