- Trending Categories
- Data Structure
- Operating System
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why and how are Python functions hashable?
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__()
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)
<type 'function'> 1265925978 1265925978
This shows that any function is hashable as it has a hash value that remains same over its lifetime.
- Are Python functions objects?
- Why do some Python functions have underscores "__" before and after the function name?
- Mathematical Functions in Python - Special Functions and Constants
- What are sex hormones? Why are they named so? State their functions.
- What are stack and unstack functions in the Python Pandas library.
- Python startswith() and endswidth() functions
- Python maketrans() and translate() functions
- How do map, reduce and filter functions work in Python?
- How and why rainbows are formed?
- What are MySQL stored functions and how can we create them?
- How MySQL FIELD() and ELT() functions are complements of each other?
- What are epithelial tissues and its functions?
- How do nested functions work in Python?
- How to produce documentation for Python functions?
- How are virtual functions implemented in C++?