Slice inconsistency?

Terry Reedy tjreedy at udel.edu
Fri Sep 26 17:28:02 EDT 2003


"Roberto A. F. De Almeida" <roberto at dealmeida.net> wrote in message
news:10c662fe.0309261245.1f35f43a at posting.google.com...
> I found that when using negative indices, the slice object passed to
> __getitem__ depends on the number of slices. An example to clarify:
>
>class a:
>    def __getitem__(self, index):
>         return index
>
> >>> b = a()
> >>> print b[:-1]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> AttributeError: a instance has no attribute '__len__'
>
> But if I pass a "multiple" slice:
>
> >>> print b[:-1,:-1]
> (slice(None, -1, None), slice(None, -1, None))

A square-bracketed subscript (index/key) is a *single* object, in this
case a tuple.  The contents of the tuple are irrelevant (for this
code).  Any  tuple will be echoed:

>>> b[1,2,3]
(1, 2, 3)

> If we add the following __len__ to class a:
>
>     def __len__(self):
>         return 42

Completely irrelevant for the processing of tuple keys.

> Is there something wrong in using slices like this in objects? A
> better way?

What you probably want is b[:-1][:-1], etc.  Each index must be
separately bracketed to access items in list of lists (etc).

Terry J. Reedy






More information about the Python-list mailing list