Antoon Pardon apardon at
Tue Jan 18 08:28:00 EST 2005

Op 2005-01-18, Nick Coghlan schreef <ncoghlan at>:
> Antoon Pardon wrote:
>> More specific the Decimal class is mutable and usable as dict key.
> It's *meant* to be immutable though. The fact that we used __slots__ instead of 
> __setattr__ to implement the immutability, so you *can* overwrite the slot 
> variables if you really want to is merely an artifact of the current Python 
> implementation.
> The limited mutability bug will disappear in Python 2.5, so it's not a good 
> example of a 'mutable' dict key (especially given that the only way to mutate it 
> is to modify private variables directly).
> And, as I've stated previously, if the issue of sane mutable keys in 
> dictionaries and sets really bugs you so much - implement identity_dict and 
> identity_set in C and lobby for their inclusion in the collections module.

I'm not bugged by its absence in Python. I'm bugged by the attitude
about them. But anyway I'm thinking about implementing a safe dictionary
that will copy whenever it would otherwise allow the risk of mutating a

> On the more general point of "don't use mutable objects with non-identity based 
> comparisons as dictionary keys", try teaching students for a while (or listen to 
> those who have):

What kind of students?

I have implemented a hash table when I was a student and its
implementation allowed the use of 'mutable' objects as a key
without a problem. It simply always made copies when appropiate
and didn't allow external access to the keys. So although the
key objects were 'mutable' there was no way a user could accidently
mutate a key.

So don't use a mutable as a dictionary key isn't so much a dictionary
limitation in general but a specific limitation of the python implementation.

And yes I understand, the current implenatation is the result of the
fact that the same dictionaries are used internally for variables in
scopes and attributes in objects and the fact that no copies are
involved gives a boost to performance. But it could be argued that
providing these same dictionaries with those semantics to the users
was a premature optimisation.

> When stating useful general principles, it is never, ever worth it to get into 
> the quibbly little details about exceptions to the principle. If students ask, 
> admit that they exist, but point out that the exceptions are rare, and not worth 
> worrying about at that point in their learning.

But don't use mutable keys is not a general principle. It is a principle
introduced by the limitations of the python implementations.

I don't like it when a good rule of thumb because of implementation
limitations is sold as a general principle.

Antoon Pardon

More information about the Python-list mailing list