Why and how are Python functions hashable?

PythonServer Side ProgrammingProgramming

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.

Example

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

Output

1265925722
3074942372
1265925722

This shows that lambda functions are hashable

Example

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.

raja
Published on 07-Dec-2017 17:40:09
Advertisements