[New-bugs-announce] [issue21598] Is __getitem__ and __len__ implementations enough to make a user-defined class sliceable?
Santoso Wijaya
report at bugs.python.org
Thu May 29 04:18:10 CEST 2014
New submission from Santoso Wijaya:
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
...
KeyboardInterrupt
>>> 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)
2
>>> 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__
IndexError
>>> t[:1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in __getitem__
IndexError
[1] https://docs.python.org/2/reference/datamodel.html#object.__getslice__
----------
components: Library (Lib)
messages: 219326
nosy: santa4nt
priority: normal
severity: normal
status: open
title: Is __getitem__ and __len__ implementations enough to make a user-defined class sliceable?
type: behavior
versions: Python 2.7
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue21598>
_______________________________________
More information about the New-bugs-announce
mailing list