Difference of hash and __hash__()

Michael Chermside mcherm at mcherm.com
Wed Sep 3 11:38:12 EDT 2003


Jeff Epler wrote:
> No, it's apparently deliberate that slices don't hash (so that
> {}[1:2] raises an error).  I think that slice(None).__hash__ is from
> object.__hash__, but this is rightfully(?) ignored by PyObject_Hash()
> which looks at tp_hash (NULL for slice objects) and tp_compare (non-NULL
> for slice objects) with the result that the object is treated as
> unhashable.

Leaving Stefan Fleiter somewhat puzzled:
> So, should I write a bugreport or not?
> Are you sure it is "rightfully ignored" or not?
> 
> Somewhat puzzled,
> Stefan

Stefan:

Go ahead and submit the bugreport. If it's desired that {}[1:2]
raises an error (and I believe Guido has been asked and has declared
that this is his desired behavior), then slice(1,2).__hash__()
should raise an exception -- to do otherwise is misleading. You
wanted to know if slices were hashable, so you tried out __hash__ --
IMHO that's the proper approach, and you shouldn't have to examine
the C code.

So submit the bugreport, but I'm guessing that slices will remain
unhashable. IIRC, Guido felt that the risk of confusion (folks 
thinking that {}[1:2] would return some part or subset of the dict) 
was greater than the utility of using slices as keys in a dict
(for which, I believe, he was unable to come up with a single
plausible use case).

-- Michael Chermside







More information about the Python-list mailing list