Rationale behind the deprecation of __getslice__?

Steven Bethard steven.bethard at gmail.com
Thu Dec 9 23:34:14 CET 2004


Fernando Perez wrote:
> Steven Bethard wrote:
> 
>>Fernando Perez wrote:
>>
>>>I was wondering if someone can help me understand why __getslice__ has been
>>>deprecated, yet it remains necessary to implement it for simple slices
>>>(i:j), while __getitem__ gets called for extended slices (i:j:k).
>>
>>I don't think this is true -- everything goes to __getitem__:
>>
[snip]
> 
> Not if you subclass builtin types like list:

Ahh, I didn't catch that your problem was with list.  Yeah, so if a 
__getslice__ exists, this is used first.  Unfortunately, by inheriting 
from list, you inherit __getslice__ from list.  Another example without 
builtin types:

 >>> class C(object):
...     def __getitem__(self, x):
...         print "C:getitem"
...     def __getslice__(self, *args):
...         print "C:getslice"
...
 >>> class D(C):
...     def __getitem__(self, x):
...         print "D:getitem"
...
 >>> d = D()
 >>> d[1]
D:getitem
 >>> d[1:2]
C:getslice
 >>> d[1:2:-1]
D:getitem

While the D class doesn't define __getslice__, it's parent class does, 
so it has the same behavior you're running into.  I don't see how to fix 
this other than overriding __getslice__ to call __getitem__ like you have.

Unfortunately, I don't think __getslice__ can be removed from list (and 
str and tuple) because of backwards compatibility constraints...

Steve



More information about the Python-list mailing list