Why Are Slice Objects Not Hashable In Python
Solution 1:
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).
Solution 2:
As a workaround, you can use the __reduce__()
method that supports pickling slice objects:
>>> s
slice(2, 10, None)
>>> s1=s.__reduce__()
>>> s1
(<class'slice'>, (2, 10, None))
While the slice is not hashable, it's representation is:
>>> hash(s1)
-5954655800066862195>>> {s1:'pickled slice'}
{(<class'slice'>, (2, 10, None)): 'pickled slice'}
And you can easily reconstitute the slice from that:
>>> slice(*s1[1])
slice(2, 10, None)
Post a Comment for "Why Are Slice Objects Not Hashable In Python"