Unfortunate exception on dict item assignment (and why aren't slices hashable?)
Bengt Richter
bokr at oz.net
Mon Jul 21 00:28:22 EDT 2003
On Sun, 20 Jul 2003 20:48:16 -0500, Jeff Epler <jepler at unpythonic.net> wrote:
>>>> {}[:] = 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:
Seems like you could (untested!)
> class X:
from types import SliceType # BTW, why is slice a builtin function, not a type?
> # ...
> def __getitem__(self, idx):
if isinstance(idx, self.SliceType): idx = (idx.start, idx.stop, idx.step)
# and adjust self.calculate_xxx to match.
> 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
>
Regards,
Bengt Richter
More information about the Python-list
mailing list