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

Ron Adam rrr at ronadam.com
Tue Aug 29 07:47:24 CEST 2006


Greg Ewing wrote:
> Ron Adam wrote:
> 
>> 1. Remove None stored as indices in slice objects. Depending on the step 
>> value, Any Nones can be converted to 0 or -1 immediately,
> 
> But None isn't the same as -1 in a slice. None means the end
> of the sequence, whereas -1 means one less than the end.

Yes, you are correct, thats one of those things I get caught on when I 
haven't had enough sleep. ;-)

 >>> 'abcdefg'[-1]
'g'

 >>> 'abcdefg'[0:-1]
'abcdef'

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

 >>> 'abcdefg'[-1:0:-1]
'gfedcb'

So None for the start index can be 0 or -1.  But for the end index it 
can't be determined.

In the first case above, the stop index would need to be one greater 
than -1 which is 0, and that causes a problem.

In the second case above, the stop index would need to be one less than 
0, then that would again cause a problem.



> I'm also not all that happy about forcing slice indices to
> be ints. Traditionally they are, but someone might want to
> define a class that uses them in a more general way.

Hmmmm, thanks for pointing this out. It sounds interesting and is 
something I hadn't thought about.  In most cases I've seen only integers 
and None are ever used.  And I'm used to seeing an exception if anything 
else is used.

 >>> '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?

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


>> Once the slice is created the Nones are not needed, valid index values 
>> can be determined.
> 
> I don't understand what you mean here. Slice objects themselves
> know nothing about what object they're going to be used to
> slice, so there's no way they can determine "valid index
> values" (or even *types* -- see above).

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?



Cheers,
    Ron






More information about the Python-3000 mailing list