Unfortunate exception on dict item assignment (and why aren't slices hashable?)

Jeff Epler jepler at unpythonic.net
Sun Jul 20 23:15:56 EDT 2003


Earlier, I [Jeff] wrote:
> > In fact, I wonder why slices *aren't* hashable.
> 
On Mon, Jul 21, 2003 at 04:49:55PM +0950, Ben Finney wrote:
> How would you store the resulting key; how would you expect it to be
> returned from keys() ?

???

Here's something that "works" today:
>>>class C: __getitem__ = lambda self, idx: idx
...
>>> C()[:]
slice(0, 2147483647, None)

But this doesn't work:
>>> d = {}
>>> s = C()[:]
>>> d[s] = None
TypeError: unhashable type

Here's what "should" happen:
>>> d[s] = None
>>> print d[s]
None
>>> print d
{slice(0, 2147483647, None): None}

I don't see what's problematic about letting slices be hashable: they
don't appear to be mutable, for instance.
>>> s.start
0
>>> s.start = -1
TypeError: readonly attribute
... it may merely be an oversight.  Hashing them as
    hash((s.start,s.stop,s.step))
might be a reasonable definition.

Jeff





More information about the Python-list mailing list