WeakKeyDictionary with tuple of objects as key

Viewed 18

I want to use a WeakKeyDictionary where the keys are tuples of other objects, e.g. of type Tuple[A,B], in such a way:

# a,b,c defined somewhere
d = WeakKeyDictionary()
d[(a, b)] = c

This does not work because: TypeError: cannot create weak reference to 'tuple' object. But even if it could create a weak ref to a tuple, you have the other problem: The tuple object here ((a,b)) is not referenced anymore, i.e. after this code, the dict d is empty again.

In principle however, having such a weak key dict to tuples should be possible. I think the behavior should be non-ambiguous and straight-forward: Whenever any part of the key gets deleted (a or b), the whole key gets removed.

How can I get this? Any easy way using the existing builtins? Or do I need to implement my own? Or is there some other library providing this?

0 Answers
Related