Quick actions

cmd+k|ctrl+k

Navigation

Languages

Object __hash__

Snippet info

Language

Python

Visibility

public

Author

apizzimenti

Created

2016-05-04T19:23:24Z

Updated

2016-05-06T20:39:36Z


'''

This is an overview of Python object hashing. A hash, or hashmap, is a data structure
that maps a key to a value. A dict is Python's implementation of a hashmap:

    dict = {
        'key': 'value'
        'key_2': 'value_2'
        'key_3': 'value_3'
        ...
        'key_n': 'value_n'
    }
    
When you try to access something in a dict, Python internally runs hash() on the key
you provide so it doesn't have to run a comparison against every key in the dict. Dicts
provide a space denoted by a hash value for each (key, value) pairing, and so 
the keys do not have to be sequentially searched.
For example:

hash('key') == 6017861245500558313

dict['key'] --> Python asks 'okay, do I have a space allocated for 6017861245500558313'?
            --> yes! return 'value'!
            
Objects, however, have many methods and properties; hashing them requires a custom
__hash__ implementation. Below are implementations of custom __hash__ and __eq__
methods.

'''
class a:
    def __init__(self, n):
        self.n = n
        
    def __keys__(self):
        return self.n
        
    def __eq__(self, other):
        return self.n == other.n
        
    def __hash__(self):
        return hash(self.__keys__())
        
b = a(1)
c = a(2)

print(hash(b), hash(c))
print(b == c)



INFO