[Python-ideas] [Python-Dev] Inclusive Range

Antoon Pardon Antoon.Pardon at rece.vub.ac.be
Tue Oct 12 09:52:39 EDT 2010


On Fri, Oct 08, 2010 at 05:05:26PM -0400, Terry Reedy wrote:
> But you really seem to be saying is "What if I sometimes want the
> end points included and sometimes do not?"  Slice syntax by itself
> cannot handle all four cases, only one, one was chosen and that was
> closed-open.
> 
> If you want flexibility, consider the following:
> 
> class my_list(list):
>     def __getitem__(self, key, include_start=True, include_stop=False):
>         if (isinstance(key,tuple) and len(key)==2 and
> isinstance(key[0], slice)
>           and isinstance(key[1],tuple) and len(key[1])==2):
>             key, (include_start, include_stop) = key
>             start,stop,stride = key.indices(len(self))
>             if include_start == False:
>                 start += 1
>             if include_stop == True:
>                 stop += 1
>             key = slice(start,stop,stride)
>             print(key)
>         return list.__getitem__(self, key)
> 
> ll = my_list(range(10))

That seems to be an undocumented feature. I didn't know it was possible
to use extra parameters after key in __getitem__. 

It also doesn't seem mentioned in the documentation:

  http://docs.python.org/reference/datamodel.html

  Object.__getitem__(self, key)

      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. For mapping types, if key
  is missing (not in the container), KeyError should be raised.

I'm a bit reluctant to rely on such an undocumented feature.

-- 
Antoon Pardon



More information about the Python-list mailing list