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

Jeff Epler jepler at unpythonic.net
Mon Jul 21 03:48:16 CEST 2003


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

I'd have expected something like 'TypeError: unslicable type'
meaning that you can't slice a dict, not that slice()s aren't hashable.

In fact, I wonder why slices *aren't* hashable.  I can imagine wanting
to write something like the following:
    class X:
        # ...
        def __getitem__(self, idx):
            if not idx in self._cache:
                # potentially expire an item and
                if isinstance(idx, slice):
                    self._cache[idx] = self.calculate_slice_expensively(idx)
                else:
                    self._cache[idx] = self.calculate_idx_expensively(idx)
            return self._cache[idx]
 
Jeff





More information about the Python-list mailing list