Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are slice objects not hashable in python

Tags:

python

Why are slice objects in python not hashable:

>>> s = slice(0, 10)
>>> hash(s)
TypeError                                 Traceback (most recent call last)
<ipython-input-10-bdf9773a0874> in <module>()
----> 1 hash(s)

TypeError: unhashable type

They seem to be immutable:

>>> s.start = 5
TypeError                                 Traceback (most recent call last)
<ipython-input-11-6710992d7b6d> in <module>()
----> 1 s.start = 5

TypeError: readonly attribute

Context, I'd like to make a dictionary that maps python ints or slice objects to some values, something like this:

class Foo:
   def __init__(self):
       self.cache = {}
   def __getitem__(self, idx):
       if idx in self.cache:
           return self.cache[idx]
       else:
           r = random.random()
           self.cache[idx] = r
           return r

As a workaround I need to special case slices:

class Foo:
   def __init__(self):
       self.cache = {}
   def __getitem__(self, idx):
       if isinstance(idx, slice):
           idx = ("slice", idx.start, idx.stop, idx.step)
       if idx in self.cache:
           return self.cache[idx]
       else:
           r = random.random()
           self.cache[idx] = r
           return r

This isn't a big deal, I'd just like to know if there is some reasoning behind it.

like image 984
Bi Rico Avatar asked May 01 '15 02:05

Bi Rico


1 Answers

From the Python bug tracker:

Patch # 408326 was designed to make assignment to d[:] an error where d is a dictionary. See discussion starting at http://mail.python.org/pipermail/python-list/2001-March/072078.html .

Slices were specifically made unhashable so you'd get an error if you tried to slice-assign to a dict.

Unfortunately, it looks like mailing list archive links are unstable. The link in the quote is dead, and the alternate link I suggested using died too. The best I can point you to is the archive link for that entire month of messages; you can Ctrl-F for { to find the relevant ones (and a few false positives).

like image 147
user2357112 supports Monica Avatar answered Sep 21 '22 01:09

user2357112 supports Monica