Any built-in ishashable method ?
tjreedy at udel.edu
Fri Jan 18 12:25:51 CET 2013
On 1/18/2013 5:36 AM, Jean-Michel Pichavant wrote:
> Hello people,
> Is there any built-in way to know if an object is a valid dictionary key ?
For the instances of a class to be properly useable as set members or
dict keys, __eq__ must return bool, __hash__ must return int, the __eq__
and __hash__ methods must define equivalence relations on the instances
of the class, and the hash relation should be a coarsening of the eq
relation. By default, for objects()s, equality is identity and hash is
id, so these condition are met.
If the instances of a class can compare equal to instances of another
class then apply the , then apply the above to the union of the classes
if they are used together in one set or dict.
An example of when the union condition was broken. We had 0.0 == 0 and
== decimal(0) but 0.0 != decimal(0). The breaking of transitivity of ==
has nasty effects when mixing floats, ints, and decimals in one
set/class. (This is fixed now.) For one thing, set((0, 0.0, decimal(0)))
had one member while set((0.0, 0, decimal(0))) had two ;-)
> I was trying to know if any custom class can be used as a dict key.
Yes, unless the __eq__ and __hash__ methods have been over-written in
the inheritance chain in a way that violates the conditions, or if the
class instances are mixed with other class instances that joint violate
> Yet I'm a little bit concerned, because last time I used invalid
> objects as keys, I got a bug that was really difficult to spot.
Yeh, see the example above ;-).
Terry Jan Reedy
More information about the Python-list