0

Python dicts/lists are not hashable but python objects are. This seems odd to me, particular because python dicts and python objects are nearly identical from a mutability stand point.

I have a couple of theories:

  • Two dicts can be equal without having the same id, and python enforces that equal instances must have the same hash. Objects don't have this behavior by default, but they can if __eq__ is overriden
  • dicts and lists are designed to be mutated. Having them hash to the same value before and after mutating is a foot-gun

What was the design justification for this language feature?

Update from comments: https://docs.python.org/3/glossary.html#term-hashable

This explains why dicts/lists aren't hashable since

Hashable objects which compare equal must have the same hash value.

But why was this rule decided on?

Kyle
  • 2,946
  • 1
  • 13
  • 11
  • 2
    Python dicts/lists *are* python objects – Chris_Rands Mar 02 '18 at 13:19
  • which makes their inability to be hashed even stranger, no? – Kyle Mar 02 '18 at 13:20
  • Your second bullet is closer to the main reason, it is too easy for mutating the object to change the hash value https://stackoverflow.com/questions/2671376/hashable-immutable – Cory Kramer Mar 02 '18 at 13:20
  • 1
    It makes your question unclear IMO. Basically hashability *approximates* immutability in Python – Chris_Rands Mar 02 '18 at 13:21
  • Arbitrary python objects are hashable, `hash(object())` returns a value while `hash({})` is an exception – Kyle Mar 02 '18 at 13:23
  • You're right, my bad; but the default is the `id` which tends not to be useful. See e.g. https://docs.python.org/3/glossary.html#term-hashable. – jonrsharpe Mar 02 '18 at 13:28

1 Answers1

2

Good article that explains hashable and equality problem. In general, I would say that decision to keep default object hashable was made because it covers more cases and still quite cheap. When doing the same for dicts and lists will produce unexpected result most of the time.

Eugene K
  • 388
  • 2
  • 9