[Python-il] elegant non contiguous slice

Alon Levy alonlevy1 at gmail.com
Fri Dec 31 08:32:31 IST 2010

On Thu, Dec 30, 2010 at 9:59 PM, Shai Berger <shai at platonix.com> wrote:
> On Thursday 30 December 2010, Alon Levy wrote:
> (edited against the top-posting)
>> On Thu, Dec 30, 2010 at 7:42 AM, Shai Berger <shai at platonix.com> wrote:
>> >
>> > class L(list):
>> >  def __getitem__(self, idx):
>> >    try:
>> >      i = iter(idx)
>> >    except TypeError:
>> >      return super(L, self).__getitem__(idx)
>> >    else:
>> >      return [self[ii] for ii in i]
>> >
>> Why not do exactly what you propose, but without using operator
>> overloading? that way it isn't
>> magic anymore, doesn't override expected behavior of the getitem
>> protocol, and still provides
>> what's wanted with almost the same amount of chars (call it slice,
>> myarr=L([0,1.2.3]); myarr.slice([1,2])==myarr([1,2]))
> It's a matter of priorities. I was trying to avoid the double brackets ("([])"
> or "[[]]"), which I find much more distasteful than the slight expansion of
> the getitem semantics. What I don't like about this is that it's very
> inefficient; and that holds regardless of the call syntax used.

Have you tried shedskin recently? it actually works. I mean, realistically, if
he actually ends up with this as a bottleneck, he could try to code it as an
iterator (no in between copy in that case), not sure if it would actually be
faster (depends really):
def slice(self, idx):
 for i in idx:
  yield self[i]

list(myarr.slice([1,2])) == myarr([1,2])

btw, he can of course have a constructor and slice operator that avoid
the double
parenthesis if you really want (which btw shedskin doesn't support yet ;), so:
def slice(self, *idx):
class myarr(list):
 def __init__(self, *items):
  super(list, self).__init__(items)

list(myarr.slice(1,2)) == myarr(1,2)

actually I think constructing a list and then giving it to the myarr
constructor (by inheritance) shouldn't copy the list. Actually I'm not
sure if it's any different then having a wrapper class.

> Shai.

Alon Levy

More information about the Python-il mailing list