Search code examples
pythonpython-3.xdel

Delete an instance from its class' dict in desctructor?


I'm trying to create a class that saves all of its instances in a dictionary:

>>> class X:
    def __new__(cls, index):
        if index in cls._instances:
            return cls._instances[index]
        self = object.__new__(cls)
        self.index = index
        cls._instances[index] = self
        return self
    def __del__(self):
        del type(self)._instances[self.index]
    _instances = {}

However, the __del__ doesn't seem to work:

>>> x = X(1)
>>> del x
>>> X._instances
{1: <__main__.X object at 0x00000000035166D8>}
>>> 

What am I doing wrong?


Solution

  • Building on Kirk Strauser's answer, I'd like to point out that, when you del x, the class' _instances still holds another reference to x - and thus it can't be garbage collected (and __del__ won't run.

    Instead of doing this kind of low-level magic, you probably should be using weakrefs, which were implemented especially for this purpose.

    WeakValueDictinary, in particular, suits your needs perfectly, and you can fill it on __init__ instead of fiddling with __new__ and __del__