Python Glossary Русский

Python 3.3+collectionsterm

collections.abc.Hashable

collections.abc — protocols

The protocol for hashable objects (has __hash__).

Syntax

isinstance(obj, collections.abc.Hashable)

Passing this check only means the type's __hash__ is not None — it does not promise that hashing will succeed. The classic counterexample is a tuple holding a list: it registers as Hashable, yet hash() raises TypeError because a tuple hashes its elements. When you need a real guarantee, calling hash() inside try/except is more honest than the isinstance test.

Examples

import collections.abc as abc
print(isinstance(1, abc.Hashable))    # → True
print(isinstance([], abc.Hashable))   # → False
print(isinstance('abc', abc.Hashable))   # → True
print(isinstance({1: 2}, abc.Hashable))   # → False
print(isinstance(([1], 2), abc.Hashable))   # → True
print(hash(([1], 2)))   # → TypeError

See also

Open in the full glossarydocs.python.orgReport an inaccuracy