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?
You need to "implement your own" in this case - and the problem is that you will need an auxiliar dictionary with stand-alone keys - so that when the time comes to del one the paired keys, you are able to find them back.
The implementation of WeakrefDicts themselves are pretty simple and straightforward, using collection.abc helpers for mappings - you could even pick the code from there and evolve it- but I think a minimal one can be done from scratch like bellow.
To be clear: this is a fresh implementation of weak-key dicts, doing exactly what you asked in the question: the keys should e any sequence of weak-referenceable objects, and when any object from the sequence is destroyed, the item is cleared in the dictionary. This is done using the callback mechanism of low-level
weakref.refobjects.And working: