[Python-Dev] __getitem__ in user defined classes

Michael Hudson mwh@python.net
21 Oct 2002 11:06:46 +0100


"Raymond Hettinger" <python@rcn.com> writes:

> 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)]

You can spell that 

        if isinstance(index, slice):
            return [x**2 for x in range(*index.indices(11))]

and, as a bonus, it'll work more often <wink> (consider
"SquaresToTen()[7::-2]", for example).

> 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

However to make omitted slice places work, you need to pass in the
length of the sequence, so I don't think this can fly.

Cheers,
M.

-- 
  We've had a lot of problems going from glibc 2.0 to glibc 2.1.
  People claim binary compatibility.  Except for functions they
  don't like.                       -- Peter Van Eynde, comp.lang.lisp