Hacker News new | ask | show | jobs
by gshulegaard 3505 days ago
I think there is a disconnect here, I showed you how you could place a mutable object as a dict key in Python. One which uses the object itself (id() property) for the hash.

> If you want something immutable just put something immutable in.

My point is what do you expect if you do this:

>>> x = (1, 2)

>>> y = (1, 2)

>>> set([x, y])

I would argue that you would expect:

>>> set([(1,2)])

Since x is equal to y. But if you base the hash by default on id, you would get:

>>> set([(1, 2), (1, 2)]) # set([x, y])

Since x and y are different instances (have different id()) properties. I would argue that it's more useful/predictable for built-ins to hash based on content rather than id().

However, you can still hash based on id() but simply creating your own object (as I demonstrated). So you get sensible defaults for built-ins but also the option of hashing mutable objects.

1 comments

We were originally talking about a dictionary key, and the purpose of an object as key in a dictionary is AFAICS to associate a value with that concrete object. Whenever I use those structures I have to solve an engineering problem, not a math problem. I would claim that's the majority of use cases, a claim that seems to be supported by how it is commonly implemented (see Java below and Javascript for two of the most common languages).

Anyway, it's configurable for example in Java (http://stackoverflow.com/questions/9440380/using-an-instance...) - default is to use the reference but you can override object methods to change that. Similarly for C#(http://stackoverflow.com/questions/634826/using-an-object-as... or http://stackoverflow.com/questions/8952003/how-does-hashset-...).

Ah I see the disconnect, I think the underlying piece I glossed over was the fact that dict objects and set objects rely on the same hashable property of objects. This is in part due to the "one way and only one way" rule of thumb of Python's language design.

For me, talking about how dicts handle hashing keys and sets hashing members are equivalent in the context of the Python language.

Given that context I was saying changing the "hashable" nature of default objects would be counter-intuitive as the new behavior would be in contrast to the expected behavior of sets and/or immutable equal types in dict keys.