[Python-3000] Making more effective use of slice objects in Py3k

Greg Ewing greg.ewing at canterbury.ac.nz
Tue Aug 29 11:14:18 CEST 2006


Ron Adam wrote:

> And in addition to that... 0 is not the beginning if the step is -1.

Negative steps are downright confusing however you
think about them. :-)

> In most cases I've seen only integers 
> and None are ever used.

Numeric uses various strange things as array indexes, such
as Ellipsis and NewAxis. I don't think it uses them as parts
of slices, but I wouldn't be surprised if they came up with
some such usage one day.

>  >>> 'abc'[1.0]
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
> TypeError: string indices must be integers
> 
> That is a string method that is generating the exception then and not 
> the slice object?

Yes, I expect so. From experimenting, it seems you can
pass anything you want to slice():

Python 2.3 (#1, Aug  5 2003, 15:52:30)
[GCC 3.1 20020420 (prerelease)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
 >>> slice(42.3, "banana", {})
slice(42.299999999999997, 'banana', {})

> But then what about the slice.indices() method?  It does generate 
> exceptions.
> 
>  >>> slc = slice(1.0)
>  >>> slc.indices(10)
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
> TypeError: slice indices must be integers

That particular method seems to require ints, yes. But
a slice-using object can extract the start, stop and step
and do whatever it wants with them.

> Ok, I hadn't considered the possibility of methods being defined to read 
> the slice object.  Do you know where I could find an example of that?

--
Greg


More information about the Python-3000 mailing list