Why are non integral builtin types allowed in python slices?
<p>I've just improving test coverage for a <a href="https://github.com/JaggedVerge/mmap_backed_array" rel="nofollow">library</a> that has to support slices and I've noticed that slices can contain non-integral types:</p>

<pre><code>&gt;&gt;&gt; slice(1, "2", 3.0)
slice(1, '2', 3.0)
&gt;&gt;&gt; sl = slice(1, "2", 3.0)
&gt;&gt;&gt; [1,2,3][sl]
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
TypeError: slice indices must be integers or None or have an __index__ method
</code></pre>

<p>This might just be my static-typing background but it seems strange to me that the builtin types without <code>__index__</code> can be passed in here without a <code>TypeError</code>. Why is this so? Would I be right in assuming that arbitrary types are allowed in order to support duck typing for types that implement <code>__index__</code>? Is the lack of a type check due to performance reasons for the most commonly used cases?</p>

<p>Prior to <a href="https://www.python.org/dev/peps/pep-0357/" rel="nofollow">PEP 357</a> was the slice in the example invalid?</p>

<p>Third-party libraries may want to implement slicing for their own objects, and there's no reason for the core language to restrict those third-party libraries to only using integers or integer-like objects (i.e., objects whose type provides the <code>__index__</code> method) in their slices. Here are two notable examples of packages using non-integers in slicing: in NumPy, some objects accept a complex step, for example:</p>

<pre><code>&gt;&gt;&gt; import numpy
&gt;&gt;&gt; numpy.mgrid[0:2:5j]
array([ 0. ,  0.5,  1. ,  1.5,  2. ])
</code></pre>

<p>And in Pandas, you can slice a <code>Series</code> or <code>Dataframe</code> object by label. That label could be a string, or a <code>datetime</code> object (for example).</p>

<pre><code>&gt;&gt;&gt; import pandas
&gt;&gt;&gt; s = pandas.Series(range(4), index=['a', 'b', 'c', 'd'])
&gt;&gt;&gt; s['b':'d']
b    1
c    2
d    3
dtype: int64
</code></pre>

<p>So it wouldn't make sense for the core language to raise an exception when constructing a slice containing non-integers; that would break the above libraries. Instead, the actual slicing operation should raise an exception if the slice components (start, stop, step) are not of the appropriate type.</p>

python python-3.x slice python-internals