slice objects vs. []
Quinn Dunkan
quinn at regurgitate.ugcs.caltech.edu
Wed May 22 17:59:04 EDT 2002
On Wed, 22 May 2002 15:12:13 -0600, Fernando Pérez <fperez528 at yahoo.com> wrote:
>Quinn Dunkan wrote:
>
>> This seems to imply that [].__getitem__ should accept a slice object.
>> Currently I am writing
>>
>> def __getitem__(self, k):
>> if type(k) is type(slice(0)):
>> return self.data[k.start:k.end]
>> else:
>> return self.data[k]
>>
>> ... which is awkward, in addition to losing k.step.
>>
>> BTW, is there any particular reason slice() is not a type? I expected to be
>> able to write 'isinstance(k, slice)'.
>>
>
>The docs are a bit outdated, I think. They don't describe __getslice__, which
>is what you want. Her's an example from my code:
Actually, they do describe __getslice__, with the words "Deprecated since
release 2.0. Support slice objects as parameters to the __getitem__() method."
<wink>
__getslice__ is still supported for backward compatibility though, but
def __getitem__(self, k): return self.data[k]
def __getslice__(self, i, j): return self.data[i:j]
... is still somewhat clumsy and still fails if you pass a step. I would like
to say
self.__getitem__ = self.data.__getitem__
More information about the Python-list
mailing list