[Python-Dev] __getitem__ in user defined classes

Raymond Hettinger python@rcn.com
Sun, 20 Oct 2002 23:03:04 -0400


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