Я не думаю, что это имеет практическое значение, но интересно попробовать:
import weakref
def callback(elem):
print(elem, "gc'ed!")
# After reading lib/weakref.py it's clear what
# WeakKeyDictionary pushes as callback self._remove,
# which constructed in __init__, so let's redefine it
class MyWeakKeyDict(weakref.WeakKeyDictionary):
def __init__(self, cb, dict=None):
super().__init__(dict)
self.cb = cb
def new_remove(el, selfref=weakref.ref(self)):
self = selfref()
if self is not None:
self.cb(el)
self._old_remove(el)
self._old_remove = self._remove
self._remove = new_remove
class C:
pass
c = C()
#d = weakref.WeakKeyDictionary()
# Use our class instead of WeakKeyDictionary
d = MyWeakKeyDict(callback)
d[c] = 0
print('Before gc', list(d.items()))
del c
print('After gc', list(d.items()))
Результат
Before gc [(<__main__.C object at 0x000002690F53A588>, 0)]
<weakref at 0x000002690F54A728; dead> gc'ed!
After gc []