range() is not the best way to check range?

Paul Boddie paul at boddie.org.uk
Fri Jul 21 09:22:28 EDT 2006


Antoon Pardon wrote:
>

[Subclasses of list or slice for ranges]

> Except that if you write your own class from scratch, you can't use
> it as a slice. For a language that is supposed to be about duck typing
> I find it strange that if I make my own class with a start, stop and
> step attribute, that python barfs on it when I want to use it as a
> slice.

[s2 has start, stop, step...]

> >>> lst[s2]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: list indices must be integers

In fact, the duck typing seems only to really work outside the
interpreter and the various accompanying built-in classes. Consider a
class similar to the one you defined with the name myslice (for
clarity) and with the apparently necessary indices method; consider it
used as follows:

>>> range(0, 10)[myslice(1, 5, 2)]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: list indices must be integers

Here, we start to believe that only traditional index or slice notation
will work. However, we did come across the built-in slice class before;
consider this:

>>> range(0, 10)[slice(1, 5, 2)]
[1, 3]

Regardless of whether myslice inherits from object or not, there's no
persuading the interpreter that it is a genuine slice, and remember
that we can't subclass slice (for some reason unknown). So, it would
appear that the interpreter really wants instances from some specific
set of types (presumably discoverable by looking at list_subscript in
listobject.c) rather than some objects conforming to some interface or
protocol, and perhaps it is implemented this way for performance
reasons.

In any case, in the core of Python some types/classes are more equal
than others, and for whatever reason the duck typing breaks down - a
case of "malbik endar" [1] that you just have to be aware of, I
suppose.

Paul

[1] http://www.sciamanna.com/island/pop/2004_07_13/280_malbik_endar.htm




More information about the Python-list mailing list