1

I want to register every instances on my class in a dictionary, keys are one of the parameter.

This seems to work, but the __del__ function fails. Here is the code :

class Test(object):
    instances = {}

    def __init__(self, id):
        self.id = id

    def launch(self):
        print("launch")
        Test.instances[self.id] = self

    def __del__(self):
        print("del")
        del Test.instances[self.id]

And here are the different outputs I get:

>>> a = Test(25)
>>> del a
del
>>> a = Test(25)
>>> a.launch()
launch
>>> del a
>>> 

I don't understand why this is happening, does someone has a suggestion?

Entilore
  • 170
  • 11
  • 1
    `del` and `__del__` have very little to do with each other; `__del__` certainly isn't for overloading the `del` operator or anything like that. – user2357112 Sep 29 '16 at 18:13
  • You probably want to use a `weakref.WeakValueDictionary` for `Test.instances`. See the documentation about it. – zvone Sep 29 '16 at 18:19

1 Answers1

2

__del__ is only called once there are no more references to the object in the code. It isn't (necessarily) called when the del keyword is used on an object.

When you launch a Test instance, you end up with 2 references -- a and an extra reference in the Test.instances dict. Doing del a only deletes the reference a. The Test.instances reference is still hanging around so __del__ won't be called.

A (possibly) better way to manage references to objects is to store weakref to objects. In this case, you'd probably make Test.instances a weakref.WeakValueDictionary.

mgilson
  • 300,191
  • 65
  • 633
  • 696