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

Chris Angelico rosuav at gmail.com
Thu Nov 26 06:04:06 EST 2015


On Thu, Nov 26, 2015 at 9:54 PM, Marko Rauhamaa <marko at pacujo.net> wrote:
> Chris Angelico <rosuav at gmail.com>:
>
>> On Thu, Nov 26, 2015 at 7:27 PM, Marko Rauhamaa <marko at pacujo.net> wrote:
>>> 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.
>
>    >>> hash([])
>    Traceback (most recent call last):
>      File "<stdin>", line 1, in <module>
>    TypeError: unhashable type: 'list'
>
> Annoying.

Yes, it's really annoying that you get an immediate exception instead
of unpredictably getting bizarre failures that depend on the exact
bucket sizes and dict size and so on. It's such a pain to get told
exactly where the problem is.

>> 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.
>
> But there's no way to enforce that with any of the myriad new classes.

Python tends to assume that programmers are intelligent people who are
prepared to fix their mistakes. As a general rule, if you define
__eq__, you should probably define __hash__ as well, and then you need
to know what you're doing; specifically, the invariant that if a==b,
hash(a)==hash(b). Python doesn't enforce that because it's impossible
to enforce.

ChrisA



More information about the Python-list mailing list