Handling slices

Michael Hudson mwh at python.net
Mon Apr 7 12:44:31 CEST 2003

Francois Pinard <pinard at iro.umontreal.ca> writes:

> Hi, Python friends.
> I'm currently using Python 2.2.1.  How does one support slices when given
> to __getitem__?  Suppose I get a slice object.  How can I use it to get
> a slice of a local array?  In other words, how one does apply a slice?

In 2.2.1, by hand, I think.

def __getitem__(self, item):
    if isinstance(item, types.SliceType):
       if item.step != 1:
          raise ValueError
       if item.start is None:
          start = 0
          start = item.start
       if item.stop is None:
          stop = len(self.local_array)
          stop = item.stop
       return self.local_array[start:stop]

I presume you don't need to be told that this is all much nicer in


  On the other hand, the following areas are subject to boycott
  in reaction to the rampant impurity of design or execution, as
  determined after a period of study, in no particular order:
    ...                              http://www.naggum.no/profile.html

More information about the Python-list mailing list