Unhashable object hashed¶
ID: py/hash-unhashable-valueKind: problemSecurity severity: Severity: errorPrecision: very-highTags: - quality - reliability - correctnessQuery suites: - python-security-and-quality.qls
Click to see the query in the CodeQL repository
If an object is used as a key in a dictionary or as a member of a set then it must be hashable, that is it must define a__hash__ method. All built-in immutable types are hashable, but mutable ones are not. Common hashable types include all numbers, strings (bothunicode andbytes) andtuple. Common unhashable types includelist,dict andset.
In order to store a key in adict orset a hash value is needed. To determine this value the built-in functionhash() is called which in turn calls the__hash__ method on the object. If the object’s class does not have the__hash__ method, then aTypeError will be raised.
Recommendation¶
Since this problem usually indicates a logical error, it is not possible to give a general recipe for fixing it. Mutable collections can be converted into immutable equivalents where appropriate. For example sets can be hashed by converting any instances ofset intofrozenset instances.
Example¶
lists are not hashable. In this example, an attempt is made to use alist as a key in a mapping which will fail with aTypeError.
deflookup_with_default_key(mapping,key=None):ifkeyisNone:key=[]# Should be key = ()returnmapping[key]
References¶
Python Standard Library:hash.
Python Language Reference:object.hash.
Python Standard Library:Mapping Types — dict.
Python Standard Library:Set Types — set, frozenset.