AppDividend
Latest Code Tutorials

Python Hash Function Example | Python hash() Method Tutorial

0

Python Hash Function Example | Python hash() Method Tutorial is today’s topic. The hash() method returns a hash value of the object if it has one. Hash values are just integers, which are used to compare the dictionary keys during a dictionary lookup quickly. In simple terms, the hash is a fixed size integer which identifies a particular value. Please note that the above definition is the simplest explanation.

Let us point out what is a fixed hash can mean? See the following points.

  1. The same data will have the same hash value.
  2. Even a slight change in the original data can result in a completely different hash value.
  3. The hash is obtained from a hash function, whose responsibility is to convert a piece of given information to the encoded hash.
  4. A number of objects can be much more than a number of hash values, and so, two objects may hash to the same hash value. It is called Hash collision. What this means is that if two objects have the same hash code, they do not necessarily have the same value.
  5. Objects hashed using hash() are irreversible, leading to loss of information.
  6. The hash() method returns hashed value only for immutable objects, hence can be used as an indicator to check for mutable/immutable objects.

Content Overview

Python Hash Function Example

A good hash function is the one function which results in the least number of collisions, meaning, No two sets of information should have the same hash values.

Internally, the hash() method calls __hash__() method of the object which is set by default for any object. We’ll look at this later.

Hash codes are the most used in when comparison for the dictionary keys is done.

Hash code of the dictionary keys is compared when a dictionary lookup is done for the specific key. Comparing hash is much faster than comparing the total key values because of the set of integers that hash function maps each dictionary key which is much smaller than the set of objects itself.

The hash() Syntax

See the below Hash method syntax.

hash(object)

The object parameter, whose hash value is to be returned (integer, string, float).

See the below example code.

# app.py

tuple_value = (21, 19, 18, 46, 29) # tuples are immutable
  
list_value = [11, 21, 31, 41, 51] # list are mutable
  
print ("The tuple hash value is : " + str(hash(tuple_value))) 
print ("The list hash value is : " + str(hash(list_value)))

See the below output.

Python Hash Function Example

 

A tuple is an immutable object that is we can create the hash value from the tuple.

A list is a mutable object that is why it throws an error like we can convert the list into hash. The list is unhashable type.

Return value from hash()

A hash() function returns the hash value of the object if it has one. If the object has the custom __hash__() method, it truncates the return value to a size of Py_ssize_t.

How hash() works in Python

See the following hash example in python.

# app.py

value = 1921
print("The integer hash value is : ", hash(value))

valueA = 19.21
print("The float hash value is : ", hash(valueA))

In the above code, we have taken two datatypes.

  1. Integer
  2. Float

Now, the hash of the integer is the integer itself, but the hash of the float number is somewhat different. See, the below output.

How hash() works in Python

 

Python hash() String

Let us start constructing the simple examples and scenarios in which the hash() method can be beneficial. In this example, we will get the hash value of a String.

# app.py

app = "Instagram"

hash1 = hash(app)
hash2 = hash(app)

print("Hash 1: %s" % hash1)
print("Hash 2: %s" % hash2)

See the below output.

Python hash() String

 

Both outputs are the same because we have used the same string for the hash.

Here is a significant catch if you rerun the same script, the hash changes, as shown below.

 

Python hash() Method Tutorial

How to define a hash() function for custom objects

Internally, the hash() function works by overriding the __hash()__ function.

It’s worth noticing that not every object is hashable (mutable collections aren’t hashable).

We can also define the __hash__() function for our custom class. That’s what we will do now. Before that, let’s point out some essential points.

See the following example.

  1. Hashable implementation should not be done for the mutable collections as key’s of the collections should be immutable for hashing.
  2. We don’t have to define the custom __eq()__ function implementation as it is defined for all objects.

See the following code example.

# app.py

class Employee:
    def __init__(self, empno, name):
        self.empno = empno
        self.name = name

    def __eq__(self, other):
        return self.empno == other.empno and self.name == other.name

    def __hash__(self):
        return hash((self.empno, self.name))


employee = Employee(21, 'Krunal')
print("The hash is: %d" % hash(employee))

See the following output.

How to define a hash() function for custom objects

 

Cases for custom hash implementation for objects.

Hash implementation of Objects
__eq__() __hash__() Description
Defined (by default) Defined (by default) If left as is, all objects compare unequal (except themselves)
(If mutable) Defined Should not be defined Implementation of hashable collection requires key’s hash value be immutable
Not defined Should not be defined If __eq__() isn’t defined, __hash__() should not be defined.
Defined Not defined Class instances will not be usable as a hashable collection.

__hash__() implicitly set to None

Raises TypeError exception if tried to retrieve the hash.

Defined Retain from Parent __hash__ = <ParentClass>.__hash__
Defined Doesn’t want to hash __hash__ = None

Raises TypeError exception if tried to retrieve the hash.

Why a mutable object cannot be Hashed

As we already know, only an immutable object can be hashed. This restriction of not allowing the mutable object to be hashed simplify the hash table a lot. Let’s understand how.

If the mutable object is allowed to be hashed, we need to update a hash table every time a value of the objects updates. What this means is that we will have to move the object to a completely different bucket. It is a very costly operation to be performed.

In Python, we have two objects that use hash tables, dictionaries, and sets:

  • A dictionary is the hash table and is called the associative array. In the dictionary, only keys are hashed and not the values. This is why the dictionary key should be the immutable object as well while values can be anything, even the list which is mutable.
  • The set contains unique objects which are hashable. If we have the non-hashable items, we cannot use the set and must instead use a list.

Finally, Python Hash Function Example | Python hash() Method Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.