[Python-3000] Making more effective use of slice objects in Py3k
Ron Adam
rrr at ronadam.com
Tue Aug 29 13:42:16 CEST 2006
Greg Ewing wrote:
> 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. :-)
Yes, and it seems to me it could be easier. Of course that would mean
changing something, and any solutions so far is in some way not perfect,
depending on how you look at it.
>> 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():
Hmm..., after playing around with it, list and string methods probably
call the slices indices() method from within __getitem__.
So it's the slices indices() method that is producing the exceptions in
both cases. If other objects allow something besides strings then they
are probably accessing the stop, start, and step indices directly and
are not going though slice.indices() to get at them.
The way it seems to work is approximately ...
s[i:j:k] -> s.__getitem__(x = slice(i,j,k)) # via the SLICE byte code
i, j, k = x.indices(len(self)) # by s.__getitem__()
The indices method does a type check and fixes the values depending on
what length is.
>> 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.
If you could sub class slice, then it would be possible to replace the
indices method and turn off the int check and/or put in your own value
check. but you wouldn't be able to use the i:j:k syntax. (maybe a good
thing)
sequence[myslice_object] # would work.
You would still need to produce int like values if you use it with
builtin types. But not with any of your own objects if you have
supplied your own __getitem__ method.
Cheers,
Ron
More information about the Python-3000
mailing list