Inconsistent equality and hashing¶
ID: py/equals-hash-mismatchKind: problemSecurity severity: Severity: warningPrecision: very-highTags: - quality - reliability - correctness - external/cwe/cwe-581Query suites: - python-security-and-quality.qls
Click to see the query in the CodeQL repository
A hashable class has an__eq__ method, and a__hash__ method that agrees with equality. When a hash method is defined, an equality method should also be defined; otherwise object identity is used for equality comparisons which may not be intended.
Note that defining an__eq__ method without defining a__hash__ method automatically makes the class unhashable in Python 3. (even if a superclass defines a hash method).
Recommendation¶
If a__hash__ method is defined, ensure a compatible__eq__ method is also defined.
To explicitly declare a class as unhashable, set__hash__=None, rather than defining a__hash__ method that always raises an exception. Otherwise, the class would be incorrectly identified as hashable by anisinstance(obj,collections.abc.Hashable) call.
Example¶
In the following example, theA class defines an hash method but no equality method. Equality will be determined by object identity, which may not be the expected behaviour.
classA:def__init__(self,a,b):self.a=aself.b=b# No equality method is defineddef__hash__(self):returnhash((self.a,self.b))
References¶
Python Language Reference:object.hash.
Python Glossary:hashable.
Common Weakness Enumeration:CWE-581.