This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Title: Is __getitem__ and __len__ implementations enough to make a user-defined class sliceable?
Type: behavior Stage:
Components: Library (Lib) Versions: Python 2.7
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: santoso.wijaya
Priority: normal Keywords:

Created on 2014-05-29 02:18 by santoso.wijaya, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (2)
msg219326 - (view) Author: Santoso Wijaya (santoso.wijaya) * Date: 2014-05-29 02:18
The reference doc for Python data model says that __getslice__ is deprecated [1], and that __getitem__ should be used instead:

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

But I'm getting the following behavior when I try it myself. Is there something I'm missing?

$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class tup(object):
...     def __getitem__(self, i):
...             if i == 0: return 0
...             if i == 1: return 1
>>> class tup(object):
...     def __getitem__(self, i):
...             if i in (0, 1): return i
...             else: raise IndexError()
...     def __len__(self):
...             return 2
>>> t = tup()
>>> len(t)
>>> t[0], t[1]
(0, 1)
>>> t[:2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __getitem__
>>> t[:1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __getitem__

msg219327 - (view) Author: Santoso Wijaya (santoso.wijaya) * Date: 2014-05-29 02:25
Hm. The docstring for __getitem__ doesn't mention it can/should be accepting slice object as argument. That's what I'm missing. Doc patch?
Date User Action Args
2022-04-11 14:58:04adminsetgithub: 65797
2014-05-29 02:29:08santoso.wijayasetstatus: open -> closed
resolution: not a bug
2014-05-29 02:25:23santoso.wijayasetmessages: + msg219327
2014-05-29 02:18:10santoso.wijayacreate