Why don't you make all of the subdictionaries WeakValueDictionary
s? Then, when the only strong reference in dict1
is removed, the weakref in the WeakValueDictionary
will cause that entry to be deleted automatically.
Example:
>>> class A: pass
...
>>> import weakref
>>> d1 = {}
>>> d2 = {'sub': weakref.WeakValueDictionary()}
>>> d1['a'] = A()
>>> d2['sub']['a'] = d1['a']
>>> del d1['a']
>>> d2['sub']['a']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/weakref.py", line 56, in __getitem__
o = self.data[key]()
KeyError: 'a'
Be sure that during your testing you don't accidentally have a local or global variable bound to your object (e.g. in your example, a
is still a local name bound to the Object()
instance, which will keep it alive). You can del
names (e.g. del a
) to ensure they are cleared.