Bug in slice type
John Machin
sjmachin at lexicon.net
Thu Aug 11 22:53:19 EDT 2005
Steven Bethard wrote:
> Bryan Olson wrote:
>
>>
>> class BuggerAll:
>>
>> def __init__(self, somelist):
>> self.sequence = somelist[:]
>>
>> def __getitem__(self, key):
>> if isinstance(key, slice):
>> start, stop, step = key.indices(len(self.sequence))
>> # print 'Slice says start, stop, step are:', start,
>> stop, step
>> return self.sequence[start : stop : step]
>>
>>
>> print range(10) [None : None : -2]
>> print BuggerAll(range(10))[None : None : -2]
>>
>> The above prints:
>>
>> [9, 7, 5, 3, 1]
>> []
>>
>> Un-commenting the print statement in __getitem__ shows:
>>
>> Slice says start, stop, step are: 9 -1 -2
>>
>> The slice object seems to think that -1 is a valid exclusive
>> bound, but when using it to actually slice, Python interprets
>> negative numbers as an offset from the high end of the sequence.
>>
>> Good start-stop-step values are (9, None, -2), or (9, -11, -2),
>> or (-1, -11, -2). The later two have the advantage of being
>> consistend with the documented behavior of returning three
>> integers.
>
>
> I suspect there's a reason that it's done this way, but I agree with you
> that this seems strange. Have you filed a bug report on Sourceforge?
>
> BTW, a simpler example of the same phenomenon is:
>
> py> range(10)[slice(None, None, -2)]
> [9, 7, 5, 3, 1]
> py> slice(None, None, -2).indices(10)
> (9, -1, -2)
> py> range(10)[9:-1:-2]
> []
>
>>> rt = range(10)
>>> rt[slice(None, None, -2)]
[9, 7, 5, 3, 1]
>>> rt[::-2]
[9, 7, 5, 3, 1]
>>> slice(None, None, -2).indices(10)
(9, -1, -2)
>>> [rt[x] for x in range(9, -1, -2)]
[9, 7, 5, 3, 1]
>>>
Looks good to me. indices has returned a usable (start, stop, step).
Maybe the docs need expanding.
More information about the Python-list
mailing list