Difference of hash and __hash__()

Michael Hudson mwh at python.net
Wed Sep 3 07:17:08 EDT 2003


Jeff Epler <jepler at unpythonic.net> writes:

> On Wed, Sep 03, 2003 at 07:35:31AM +1000, Delaney, Timothy C (Timothy) wrote:
> > > From: Terry Reedy [mailto:tjreedy at udel.edu]
> > > 
> > > "Stefan Fleiter" <stefan.fleiter at web.de> wrote in message
> > > news:bj2nv5$hna$1 at news.web.de...
> > > 
> > > > under Python 2.2.2:
> > > >
> > > >  >>> s = slice(None,5,None)
> > > >  >>> hash(s)
> > > > Traceback (most recent call last):
> > > >    File "<stdin>", line 1, in ?
> > > > TypeError: unhashable type
> > > >  >>> s.__hash__()
> > > > 136775584
> > > >
> > > > Can anybody explain this?
> > > 
> > > It looks like a bug.  Extended slices were added for use by Numerical
> > > Python.  It may never have tried to hash them or only done so only
> > > through the C equivavlent of s.__hash__.  Extended slicing of
> > > sequences was, I believe, only added in 2.3.
> > 
> > Looks like a bug to me too. Stefan, please raise a bug report on Sourceforge (or it will get lost). Preferably add a patch and test suite ;)
> > 
> > Tim Delaney
> 
> 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.

That's odd.  I would have expected PyType_Ready to copy the tp_hash
method down from PyObjectType.tp_hash to PySliceType.tp_hash.  Of
course, I haven't read the code for PyType_Ready particularly
recently, and don't know if it's ever called on PySliceType...

Cheers,
mwh

-- 
  I'm not sure that the ability to create routing diagrams 
  similar to pretzels with mad cow disease is actually a 
  marketable skill.                                     -- Steve Levin
               -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html




More information about the Python-list mailing list