Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does list slicing hook into __getitem__? [duplicate]

>>> class List(list):
...     def __getitem__(self, i):
...         print i, type(i)
...         return super(List, self).__getitem__(i)
...     
>>> x = List([0,1,2,3])
>>> x[1:3:]
slice(1, 3, None) <type 'slice'>
[1, 2]
>>> x[1:3]
[1, 2]

Why the second case doesn't use List.__getitem__? What does it use instead?

>>> x[::]
slice(None, None, None) <type 'slice'>
[0, 1, 2, 3]
>>> x[:]
[0, 1, 2, 3]

Same again, why discrepancy here aren't these both slicing operations?

like image 573
wim Avatar asked Feb 27 '26 08:02

wim


1 Answers

The language reference says it all. Specifically:

Deprecated since version 2.0 : Support slice objects as parameters __getitem__() method. (However, built-in types in CPython currently still implement __getslice__(). Therefore, you have to override it in derived classes when implementing slicing.)

and:

Called to implement evaluation of self[i:j] ...

Note it doesn't handle self[i:j:] ...

like image 200
mgilson Avatar answered Mar 01 '26 21:03

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!