[docs] [issue21785] __getitem__ and __setitem__ try to be smart when invoked with negative slice indices

eryksun report at bugs.python.org
Tue Jun 17 09:59:30 CEST 2014


eryksun added the comment:

Refer to the documentation for deprecated __getslice__ when slicing an instance of a classic class:

https://docs.python.org/2/reference/datamodel.html#object.__getslice__

The SLICE+3 implementation (apply_slice) calls PySequence_GetSlice if both index values can be converted to Py_ssize_t integers and if the type defines sq_slice (instance_slice for the "instance" type). The "instance" type is used for an instance of a classic class. This predates unification of Python classes and types.

apply_slice
http://hg.python.org/cpython/file/f89216059edf/Python/ceval.c#l4383

PySequence_GetSlice
http://hg.python.org/cpython/file/f89216059edf/Objects/abstract.c#l1995

instance_slice
http://hg.python.org/cpython/file/f89216059edf/Objects/classobject.c#l1177

A new-style class, i.e. a class that subclasses object, would have to define or inherit __getslice__ in order for the C sq_slice slot to be defined. But __getslice__ is deprecated and shouldn't be implemented  unless you have to override it in a subclass of a built-in type. 

When sq_slice doesn't exist, apply_slice instead calls PyObject_GetItem with a slice object:

    class A(object):
        def __getitem__(self, index):
            return index.start
        def __len__(self):
            return 10

    >>> A()[-1:10]
    -1

By the way, you don't observe the behavior in Python 3 because it doesn't have classic classes, and the __getslice__, __setslice__, and __delslice__ methods are not in its data model.

----------
components: +Interpreter Core -Documentation
nosy: +eryksun

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue21785>
_______________________________________


More information about the docs mailing list