slice objects vs. []
Chris Liechti
cliechti at gmx.net
Wed May 22 18:20:53 EDT 2002
quinn at regurgitate.ugcs.caltech.edu (Quinn Dunkan) wrote in
news:slrnaeo558.eje.quinn at regurgitate.ugcs.caltech.edu:
> 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>
that __getitem__ does not work with slices, aplies only built-in types and
subclasses of it. i think this is rooted in the C implementation of those
object (the two methods are still separate there) that might change when
the type/class unification gets further or in Python 3.0.
however it works perfectly for user defines classes, as described in the
docs:
>>> class A:
... def __getitem__(self, item):
... print item
...
>>> a=A()
>>> a[1:2]
slice(1, 2, None)
> __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__
>
--
Chris <cliechti at gmx.net>
More information about the Python-list
mailing list