On Thu, Nov 26, 2015 at 7:27 PM, Marko Rauhamaa <ma...@pacujo.net> wrote: > Chris Angelico <ros...@gmail.com>: > >> On Thu, Nov 26, 2015 at 5:52 PM, Marko Rauhamaa <ma...@pacujo.net> wrote: >>> Nothing prevents using mutable objects as keys in Python. >> >> Sure, you _can_. But if the key's hash changes between dict insertion >> and retrieval, all manner of invariants will break, and likewise if >> two equal objects have different hashes. From which you can deduce >> logically that any object used as a key must remain (not) equal to >> everything that it was (not) equal to from that time until it is >> looked up... which basically means its value mustn't change. It must >> be immutable. > > What I'm saying is that Python does not prevent mutable keys but tries > to do that with lists and tuples. > > I think Python should stop trying. > > I have wanted to use lists as keys, and there should be no reason to > allow mutable tuples. It should be enough to say that the behavior of a > dictionary is undefined if a key should mutate on the fly.
Python defines dict-key-validity as being synonymous with hashability. It's up to the class author to make sure the object's hash is useful. Behaviour being undefined works just fine [1] in C. It's not so popular in Python. I don't think we want to have myriad new and experienced programmers trying to figure out why square brackets in dict keys are usually fine but occasionally not. ChrisA [1] For some definition of "fine", anyway. -- https://mail.python.org/mailman/listinfo/python-list