2 ms·
> Because I'm pretty sure that it's possible to use mutable objects as keys in general. The users just have to observe restrictions: like don't insert the keys
by catnaroek 10y ago
> Because I'm pretty sure that it's possible to use mutable objects as keys in general. The users just have to observe restrictions: like don't insert the keys into the dictionary and then mutate them while they are in the dictionary and expect the dictionary to still work fine.
In other words, mutable objects don't work as keys, and pretending they do requires unenforced conventions to preserve the integrity of the dictionary abstraction.
> Objects can also be used as keys even if they are mutated while in the dictionary, if identity-based equality is used for the dictionary; i.e. two keys are equal if they are actually one and the same object, and not just two similar objects.
The fundamental problem is very simple: dictionary keys have to be values, not objects, and Python simply doesn't have compound values. There is no such thing as “the list [1,2,3]” in Python: you just have one or more objects whose current state happens to be the sequence 1,2,3. The very next moment, their states might be different sequences. Object identities are first-class values in Python, but identities are primitive and indecomposable - not compound!