Name
__hash__
Synopsis
__hash__(self)
The
hash(
x
)
built-in function call, and using x
as a
dictionary key (typically,
D
[
x
]
where D
is a dictionary), call
x
.__hash__( )
.
__hash__
must return a 32-bit
int
such that
x
==
y
implies
hash(
x
)==hash(
y
)
, and
must always return the same value for a given object.
When __hash__
is absent,
hash(
x
)
and using x
as a dictionary key call
id(
x
)
instead, as long as __cmp__
and __eq__
are also absent.
Any x
such that
hash(
x
)
returns a result, rather than raising an exception, is known as a
hashable
object
. When
__hash__
is absent, but __cmp__
or __eq__
is present,
hash(
x
)
and using x
as a dictionary key raise an
exception. In this case, x
is not hashable
and cannot be a dictionary key.
You normally define __hash__
only for immutable
objects that also define __cmp__
and/or
__eq__
. Note that, if there exists any
y
such that
x
==
y
, even if
y
is of a different type, and both
x
and y
are
hashable, you must ensure that
hash(
x
)==hash(
y
)
.
Get Python in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.