[Python-Dev] Ranges

Finn Bock bckfnn@worldonline.dk
Wed, 12 Jul 2000 21:48:11 GMT


[Paul Prescod]

>Ka-Ping Yee wrote:
>> 
>>     >>> [0,1,2,3,4,5,6,7,8,9,10][0:5:2]
>>     [0, 2, 4]
>
>Well, today this is syntactically correct but it doesn't work as you (or
>I) predict. I don't know if that's because nobody has implemented it yet
>or if extended slices mean something other than what I think you and I
>think they should mean

In current JPython:

JPython 1.1+07 on java1.3.0 (JIT: null)
Copyright (C) 1997-1999 Corporation for National Research Initiatives
>>> [0,1,2,3,4,5,6,7,8,9,10][0:5:2]
[0, 2, 4]



[Ka-Ping Yee}

>Ah, yes: http://www.python.org/pipermail/python-dev/2000-July/012681.html
>
>The issues were
>
>    - handling [:] and [::] consistently
>    - allowing non-integer indices
>    - letting user-defined objects do their own handling of negative indices
>
>I believe the two possibilities were
>
>    __getitem__ gets either an index or a special slice object
>    __getslice__ is deprecated (when missing, __getitem__ gets the slice args)
>
>and
>
>    __getitem__ always gets an index
>    __getslice__ gets three arguments, all optional, defaulting to None
>
>The latter isn't backward-compatible, but it makes a heckuva lot
>more sense.

AFAICT JPython already follows the first of the two possibilities.

(I'm not suggesting what python-the-language should do but I too find
the current behaviour of item/slice is IMO confusing).

regards,
finn


JPython 1.1+07 on java1.3.0 (JIT: null)
Copyright (C) 1997-1999 Corporation for National Research Initiatives
>>>
>>> class S1:
...   def __getitem__(self, i):
...     print "s1.__getitem__", i
...
>>> a = S1()
>>>
>>> a[1]
s1.__getitem__ 1
>>> a[:]
s1.__getitem__ None:None:1
>>> a[1:2]
s1.__getitem__ 1:2:1
>>> a[1:2:3]
s1.__getitem__ 1:2:3
>>> a['a':'z']
s1.__getitem__ 'a':'z':1
>>> a['a':'z':2]
s1.__getitem__ 'a':'z':2
>>>
>>>
>>> class S2:
...   def __getslice__(self, i, a):
...     print "s2.__getslice__", i, a
...   def __len__(self):
...     return 10
...
>>> a = S2()
>>>
>>> a[1]
Traceback (innermost last):
  File "<console>", line 1, in ?
AttributeError: __getitem__
>>> a[:]
s2.__getslice__ 0 2147483647
>>> a[1:2]
s2.__getslice__ 1 2
>>> a[1:2:3]
Traceback (innermost last):
  File "<console>", line 1, in ?
AttributeError: __getitem__
>>> a['a':'z']
s2.__getslice__ a z
>>> a['a':'z':2]
Traceback (innermost last):
  File "<console>", line 1, in ?
AttributeError: __getitem__
>>> a[-1:4]
s2.__getslice__ -1 4
>>>
>>> class S3:
...   def __getitem__(self, i):
...     print "s3.__getitem__", i
...   def __getslice__(self, i, a):
...     print "s3.__getslice__", i, a
...
>>> a = S3()
>>>
>>> a[1]
s3.__getitem__ 1
>>> a[:]
s3.__getslice__ 0 2147483647
>>> a[1:2]
s3.__getslice__ 1 2
>>> a[1:2:3]
s3.__getitem__ 1:2:3
>>> a['a':'z']
s3.__getslice__ a z
>>> a['a':'z':2]
s3.__getitem__ 'a':'z':2
>>>