Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Why and how are Python functions hashable?

I have a function f() and a lambda function lambda x:1 as follows

def f():pass
m = lambda x:1

Are these functions or all functions hashable?


1 Answer
Rajendra Dharmkar

An object is said to be hashable if it has a hash value that remains the same during its lifetime. It has a __hash__() method and it can be compared to other objects. For this, it needs the __eq__() or __cmp__()method. If hashable objects are equal when compared, then they have same hash value.

Being hashable renders an object usable as a dictionary key and a set member as these data structures use hash values internally.

All immutable built-in objects in python are hashable. Mutable containers like lists and dictionaries are not hashable while immutable container tuple is hashable

Objects which are instances of user-defined classes are hashable by default; they all compare unequal (except with themselves), and their hash value is derived from their id().

The hash is apparently not necessarily the ID of the function: Consider given lambda function.

m = lambda x: 1
print hash(m)
print id(m)
print m.__hash__()

OUTPUT

1265925722
3074942372
1265925722

This shows that lambda functions are hashable

Now let us consider given function f() as follows

def f():pass
print type(f)
print f.__hash__()
print hash(f)

OUTPUT

<type 'function'>
1265925978
1265925978

This shows that any function is hashable as it has a hash value that remains same over its lifetime.

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.