Negative array indicies and slice()

andrewr3mail at gmail.com andrewr3mail at gmail.com
Mon Oct 29 04:24:30 EDT 2012


On Sunday, October 28, 2012 9:44:56 PM UTC-7, alex23 wrote:
> On Oct 29, 2:09 pm, Andrew <andrewr3m... at gmail.com> wrote:
> 
> > I use this arbitrary range code *often* so I need a general purpose solution.
> 
> > I looked up slice() but the help is of no use, I don't even know how I might
> 
> > overload it to embed some logic to concatenate ranges of data; nor even if
> 
> > it is possible.
> 
> 
> 
> Slices are passed in if provided to __getitem__/__setitem__/
> 
> __delitem__, so you'd need to override it at the list level:
> 
> 
> 
>     class RangedSlicer(list):
> 
>         def __getitem__(self, item):
> 
>             # map item.start, .stop and .step to your own semantics
> 
> 
> 
> Then wrap your lists with your RangedSlicer class as needed.

Hmmm...

I began a test in an interactive shell:
>>> class RangedSlicer(list):
...     def __getitem__(self,item):
...             print item
... 
>>> a=[1,2,3,4,5]
>>> a.__getitem__( slice(1,5) )
[2, 3, 4, 5]

Very odd...  I would have expected [1,2,3,4]

>>> a.__getitem__( slice(1,8) )
[2, 3, 4, 5]

So, slice() somehow was truncated although it ought to have been executed first, and passed to __getitem__() before __getitem__ could affect it.
That requires some tricky programming!

Not only that, but,
a.__getitem__( xrange[1,8] )
Causes an exception before the __getitem__ shadowing received it.

I don't see how I can over-ride it with your suggestion, but that's very inconsistent.... for your idea seems to be normal python that would work for user defined classes.




More information about the Python-list mailing list