Unhashable object hashed¶
ID: py/hash-unhashable-value Kind: problem Severity: error Precision: very-high Tags: - reliability - correctness Query 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 (both
tuple. Common unhashable types include
In order to store a key in a
set a hash value is needed. To determine this value the built-in function
hash() is called which in turn calls the
__hash__ method on the object. If the object’s class does not have the
__hash__ method, then a
TypeError will be raised.
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 of
lists are not hashable. In this example, an attempt is made to use a
list as a key in a mapping which will fail with a
def lookup_with_default_key(mapping, key=None): if key is None: key =  # Should be key = () return mapping[key]
Python Standard Library: hash.
Python Language Reference: object.hash.
Python Standard Library: Mapping Types — dict.
Python Standard Library: Set Types — set, frozenset.