The X.__getitem__(key)
allows key
to be a slice
if supported by the X class. key
can be an arbitrary class with a key.__index__()
method. But if key
is, for example, a range
object, that doesn’t work.
I propose a new special method __slice__(self)
which returns a slice
object (or anything else that has a __slice__()
method. This will supply the value of key.__slice()
as the key in X[key]
.
For example:
l = list(range(11)
class S:
def __slice__(self): return slice(1, 9, 3)
l[S()]
>>> [1, 4, 7]
l[range(1, 20, 3) # if range has a __slice__() method
>>> [1, 4, 7, 10]
In some of my own code I have something like this:
class Interval:
def __init__(self, start, stop):
self.start, self.stop = start, stop
def applyto(self, container):
return container[self.start ; self.stop]
def __slice__(self):
return slice(self.start, self.stop)
I = Interval(2, 10)
L = list(range(100))
I.applyto(L)
>>>
[2, 3, 4, 5, 6, 7, 8, 9]
I would like to be able to say L[I]
, but I can only say I.applyto(L)
Obviously, this would be a lot easier to understand.
If an object has both a __index__
and a __slice__
method, I suppose that this should be a TypeError
, but this could be up for discussion.
Looking for an adopter
I don’t plan to follow this forum to see if it gets any traction. I only want to put this idea out there and get on with other things.
So someone should please take on the task of posting an Issue with this suggestion if it appears to be popular enough.