dictionary mutability, hashability, __eq__, __hash__

Veek M vek.m1234 at gmail.com
Sun Nov 27 04:53:06 EST 2016


I was reading this: http://stackoverflow.com/questions/4418741/im-able-to-use-a-mutable-object-as-a-dictionary-key-in-python-is-this-not-disa

In a User Defined Type, one can provide __hash__ that returns a integer 
as a key to a dictionary.

so: d = { key : value }

What is the significance of __eq__ in this regard? Why does the article 
state:

"A class that overrides __eq__() and does not define __hash__() will 
have its __hash__() implicitly set to None. '

Is this behavior like __len__ and __bool__ wrt Boolean Expressions?
If one does: if x < y and __bool__ is not defined then __len__ is 
checked. Here, if __hash__ is undefined __eq__ is checked? What does he 
mean by 'overrides __eq__'??


Also didn't follow this 
" For classes you write, this method defaults to returning a value based 
off id(self), and *********** if equality is not determined by identity 
for those classes, you may be surprised by using them as keys: 
*******************"

"The requirement is that the hash of an object doesn't change over time, 
and ********* that it keeps comparing equal (==) with its original 
value. **************************"

Also if one can do x.a = 10 or 20 or whatever, and the class instance is 
mutable, then why do books keep stating that keys need to be immutable?
After all, __hash__ is the guy doing all the work and maintaining 
consistency for us. One could do:

class Fruit:
  editable_value = ''
def __hash__(self):
 if 'apple' in self.value: 
   return 10
 elif 'banana' in self.value:
   return 20


 and use 'apple' 'bannana' as keys for whatever mutable data..
Are the books wrong?




More information about the Python-list mailing list