Late-binding of function defaults (was Re: What is a function parameter =[] for?)

Chris Angelico rosuav at gmail.com
Thu Nov 26 03:34:47 EST 2015


On Thu, Nov 26, 2015 at 7:27 PM, Marko Rauhamaa <marko at pacujo.net> wrote:
> Chris Angelico <rosuav at gmail.com>:
>
>> On Thu, Nov 26, 2015 at 5:52 PM, Marko Rauhamaa <marko at 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.



More information about the Python-list mailing list