[Python-bugs-list] [ python-Bugs-442813 ] 2.2a1: list.__getitem__ and index<0

noreply@sourceforge.net noreply@sourceforge.net
Fri, 17 Aug 2001 14:57:57 -0700


Bugs item #442813, was opened at 2001-07-19 10:31
You can respond by visiting: 
http://sourceforge.net/tracker/?func=detail&atid=105470&aid=442813&group_id=5470

Category: Type/class unification
Group: Python 2.2
>Status: Closed
>Resolution: Fixed
Priority: 5
Submitted By: Walter Dörwald (doerwalter)
Assigned to: Guido van Rossum (gvanrossum)
Summary: 2.2a1: list.__getitem__ and index<0

Initial Comment:
list.__getitem__ doesn't handle negative indizes when 
called directly:
>>> x = [1]
>>> list.__getitem__(x, -1)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IndexError: list index out of range

----------------------------------------------------------------------

>Comment By: Guido van Rossum (gvanrossum)
Date: 2001-08-17 14:57

Message:
Logged In: YES 
user_id=6380

Fixed in typeobject.c rev. 2.42.

----------------------------------------------------------------------

Comment By: Walter Dörwald (doerwalter)
Date: 2001-08-02 09:30

Message:
Logged In: YES 
user_id=89016

BTW, __setslice__  has the same problem:
>>> x = [1,2,3,4]
>>> x.__setslice__(-2,-1, [5])
>>> x
[5, 1, 2, 3, 4]


----------------------------------------------------------------------

Comment By: Guido van Rossum (gvanrossum)
Date: 2001-07-20 13:33

Message:
Logged In: YES 
user_id=6380

This is deeper than it seems.

The list object  never interprets negative indices -- that's
all done under the covers of the implementation in
PySequence_GetItem().

So list.__getitem__(), which is a very thin wrapper around
the list object's tp_as_sequence->sq_item function
(list_item in listobject.c), also doesn't interpret negative
indices.

But because __getitem__ is ambiguous (it can be a sequence
or a mapping operation, with slightly different semantics),
when you define a subclass that implements __getitem__, and
you pass an instance of that subclass a negative index, the
special handling of negative indices is skipped, so a[-1]
ends up calling a.__getitem__(-1).

This is not good.  I'll have to think about a way out of
this dilemma. Moving the negative index handling into the
objects is an option, but this might break with 3rd party
sequence objects. Doing the negative index handling twice
(once in PySequence_GetItem() and again in the object) is
bad, because it changes the semantics of very large negative
indices.


----------------------------------------------------------------------

You can respond by visiting: 
http://sourceforge.net/tracker/?func=detail&atid=105470&aid=442813&group_id=5470