This is an example of Python's behavior with negative numbers passed in slices:
>>> class test:
... def __getitem__(self, sl):
... print sl.start, sl.stop, sl.step
...
>>> t = test()
>>> t[0:0:0]
0 0 0
>>> t[-1:0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: test instance has no attribute '__len__'
>>> def __len__(self): return 100
...
>>> test.__len__ = __len__
>>> t[-1:0]
99 0 None
>>>
I want to do my own handling with negative indexes. How can I make Python stop deciding on the slice indexes automagically?
In Python 2.x, you need to use new-style classes by subclassing
object
, then you get the original parameters of the slice:Prior to 2.x, there was a dedicated method for slicing,
__getslice__
, which is still supported for in Python 2.x and does the interpolation using__len__
:(emphasis mine)