Would I be right in assuming that arbitrary types are allowed in order to support duck typing for types that implement __index__
?
There's no actual reason as to why you should restrict the types passed when initializing slice
objects. Exactly as stated in the rational for PEP 357
, numpy
and the numeric types it utilizes can't inherit from object so strict issubclass
checks of the type passed will make them unusable as index values. So duck typing is employed, if it defines the appropriate method (__index__
), it's usable.
Also take note that this (the presence of __index__
) is enforced only when applying the slice (as you saw, the TypeError
was raised during the __getitem__
, i.e list_subscript
) operation when PySlice_GetIndicesEx
is called to try and get the values you passed.
The slice objects initializer makes no discrimination on what type it accepts, all PyObject
's can apply as can be seen from its signature:
PyObject *
PySlice_New(PyObject *start, PyObject *stop, PyObject *step)
{
/* rest omitted */
Prior to PEP 357
was the slice in the example invalid?
I just built a 2.4
version of Python and tested it (PEP 357
appeared in 2.5
if I'm not mistaken), again the check if the arguments are numeric is not done during initialization but when __getitem__
is invoked; the only thing that differs is the exception message which doesn't make any notice about the __index__
dunder (which then obviously didn't exist):
Python 2.4 (#1, Sep 11 2016, 18:13:11)
[GCC 5.4.0 20160609] on linux4
Type "help", "copyright", "credits" or "license" for more information.
>>> s = slice(0, Ellipsis)
>>> [1, 2, 3][s]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: slice indices must be integers