Slices when extending python with C++

Ian Kelly ian.g.kelly at gmail.com
Tue Dec 27 18:47:25 EST 2011


2011/12/27  <rozelak at volny.cz>:
> Hallo,
> I have kind of special question when extening python with C++
> implemented modules.
>
> I try to implement a class, behaving also like an array. And I need
> to implement slice-getters. I implemented PySequenceMethods.sq_slice
> to get "simple" slices like:
>
> myobj[x:y]
>
> It works perfectly, without problems. But now I have a problem when
> need to access the array with "special" slices, like:
>
> myobj[x:y:step]
> myobj[::-1]  # to revert the array
>
> I would like to ask which method must be implemented to get this
> "special" slice getters. The "simple" slice
> PySequenceMethods.sq_slice getter accepts only two indexes - from,
> to, but not a step (which would solve the issue).

I'm not entirely certain about the C API, but in Python the
__getslice__ and __setslice__ methods do not support extended slicing
and have been deprecated and removed in Python 3.  The practice
instead is to implement __getitem__ and __setitem__ and check the type
of the key object passed in.  For slicing, the object passed in will
be a slice object, which contains start, stop, and step attributes.
For example:

class MySequence(object):
    def __getitem__(self, key):
        if isinstance(key, slice):
            # return a subsequence using key.start, key.stop, key.step
        else:
            # return a single item indexed by key

HTH,
Ian



More information about the Python-list mailing list