__getitem__ in user defined classes

In Py2.3, __getitem__ conveniently supports slices for builtin sequences: 'abcde'.__getitem__(slice(2,4)) For user defined classes to emulate this behavior, they need to test the index argument to see whether it is a slice and then loop over the slice indices like this: class SquaresToTen: """Acts like a list of squares but computes only when needed""" def __len__(self): return 11 def __getitem__(self, index): if isinstance(index, slice): return [x**2 for x in range(index.start, index.stop, index.step)] else: return index**2 print SquaresToTen()[2] print SquaresToTen()[7:1:-2] This could be simplified somewhat by making slices iterable so that the __getitem__ definition looks more like this: def __getitem__(self, index): if isinstance(index, slice): return [x**2 for x in index] else: return index**2 Raymond Hettinger

Raymond Hettinger <python@rcn.com>:
This could be simplified somewhat by making slices iterable
Hmmm... if slices were iterable, they'd behave a lot like xrange objects. Perhaps slice == xrange could be true in some future Python? Greg Ewing, Computer Science Dept, +--------------------------------------+ University of Canterbury, | A citizen of NewZealandCorp, a | Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. | greg@cosc.canterbury.ac.nz +--------------------------------------+

On Mon, Oct 21, 2002 at 04:39:53PM +1300, Greg Ewing wrote:
http://python.org/sf/575515 , rejected. Oren

Note that slice() isn't limited to integers -- that's up to whoever interprets the slice instance. But iteration really should only support ints. --Guido van Rossum (home page: http://www.python.org/~guido/)

Raymond Hettinger <python@rcn.com>:
This could be simplified somewhat by making slices iterable
Hmmm... if slices were iterable, they'd behave a lot like xrange objects. Perhaps slice == xrange could be true in some future Python? Greg Ewing, Computer Science Dept, +--------------------------------------+ University of Canterbury, | A citizen of NewZealandCorp, a | Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. | greg@cosc.canterbury.ac.nz +--------------------------------------+

On Mon, Oct 21, 2002 at 04:39:53PM +1300, Greg Ewing wrote:
http://python.org/sf/575515 , rejected. Oren

Note that slice() isn't limited to integers -- that's up to whoever interprets the slice instance. But iteration really should only support ints. --Guido van Rossum (home page: http://www.python.org/~guido/)
participants (4)
-
Greg Ewing
-
Guido van Rossum
-
Oren Tirosh
-
Raymond Hettinger