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

Erik Max Francis max at alcyone.com
Mon Jul 21 06:01:45 CEST 2003


Ben Finney wrote:

> You're not requesting to slice a dict; you're requesting to reference
> an
> element of a dict with : as the key.

No he's not, that would be

	{}[':']

Here's the proof; actually, the error has nothing to do with assignment,
it just has to do with slicing:

>>> {}[:]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unhashable type

What this really does is build a slice object and try that:

>>> {}[slice(0)]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unhashable type

So the complaint is that the index it's trying to lookup can't be
hashed.  And that's because slices aren't hashable:

>>> hash(slice(0))
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unhashable type

Though there's no doubt at all that's a confusing error.  But slicing is
a feature of a _sequence_ type, not a _mapping_ type.

-- 
   Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
 __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ It is much safer to obey than to rule.
\__/  Thomas a Kempis




More information about the Python-list mailing list