slice objects vs. []

Quinn Dunkan quinn at regurgitate.ugcs.caltech.edu
Wed May 22 16:35:50 EDT 2002


Of __getitem__, the langref says, in 3.3.4:

    Called to implement evaluation of self[key]. For sequence types, the
    accepted keys should be integers and slice objects.  Note that the special
    interpretation of negative indexes (if the class wishes to emulate a
    sequence type) is up to the __getitem__() method. If key is of an
    inappropriate type, TypeError may be raised; if of a value outside the set
    of indexes for the sequence (after any special interpretation of negative
    values), IndexError should be raised. Note: for loops expect that an
    IndexError will be raised for illegal indexes to allow proper detection of
    the end of the sequence.


This seems to imply that [].__getitem__ should accept a slice object.
Currently I am writing

    def __getitem__(self, k):
        if type(k) is type(slice(0)):
            return self.data[k.start:k.end]
        else:
            return self.data[k]

... which is awkward, in addition to losing k.step.

BTW, is there any particular reason slice() is not a type?  I expected to be
able to write 'isinstance(k, slice)'.

BTW again, shouldn't that Note mention the new iteration protocol?



More information about the Python-list mailing list