Why can't slice use non-int. indices?

Paul Winkler slinkp23 at yahoo.com
Thu May 31 14:31:39 EDT 2001


This is on python 2.1.

>>> a = []
>>> a[3:4]
[]
>>> a[3.2: 4]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: slice indices must be integers


Now that's obviously correct for lists, since they are indexed by
integers. But the same thing happens with any class that defines
__getitem__. Annoying since I see nothing in the docs that says
slice indices must be integers (or even numbers). So instead of
using a slice, I use some other method to do what I want. That's
OK, but annoying, since these are things I'm using a LOT and the
slice notation seems so obvious for what I'm doing.

Is there a good reason that python must always insist on integer
slice indices, even for objects that aren't organized by integer
indices?

How hard / desirable would it be to remove this (undocumented?)
restriction from python? This could be 100% backwards compatible
since built-in lists could still raise a TypeError with non-int
indices.

Does anyone else think this would be A Good Thing?

An example application : a UserDict subclass that defines
__getslice__ such that

>>> some_instance["m":"o"]

... returns all items keyed with strings whose first letter is at
least "m" but less than "o" in alphabetical order.

Am I weird for thinking this sort of thing is an obvious
application for slice notation?  Or that
some_instance.slice(end="c") is a burdensome way to have to
implement this kind of thing?

Should I submit a PEP or just live with it?

--PW



More information about the Python-list mailing list