Rationale behind the deprecation of __getslice__?

Steven Bethard steven.bethard at gmail.com
Thu Dec 9 22:35:15 CET 2004


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__:

 >>> class C(object):
...     def __getitem__(self, *args, **kwds):
...         print args, kwds
...
 >>> c = C()
 >>> c[1]
(1,) {}
 >>> c[1:2]
(slice(1, 2, None),) {}
 >>> c[1:2:-1]
(slice(1, 2, -1),) {}

All you have to do is check the type of the single argument to __getitem__:

 >>> class C(object):
...     def __getitem__(self, x):
...         if isinstance(x, slice):
...             return x.indices(10)
...         else:
...         	return x
...
 >>> c = C()
 >>> c[1]
1
 >>> c[1:2]
(1, 2, 1)
 >>> c[1:2:-1]
(1, 2, -1)

Steve



More information about the Python-list mailing list