referencing disjoint array indexes

Alex Martelli aleax at aleax.it
Mon Nov 11 08:18:19 EST 2002


Padraig Brady wrote:

> Hi,
> 
> Is there any way you can do something like
> 
> size, mtime = os.stat()[8,6]

Sure, e.g.:

def getat(alist, *idx):
    return [alist[x] for x in idx]

size, mtime = getat(os.stat(), 8, 6)


I saw you mentioning in a followup that this "doesn't support slicing".  
Actually, not supporting slicing polymorphically with indexing is a
problem with Python 2.2's builtin sequences (which were still using
the C-level equivalent of the obsolete, deprecated __getslice__ &c
methods), already overcome in Python 2.3 -- in 2.3a0:

>>> def getat(alist, *idx): return [alist[x] for x in idx]
...
>>> getat('four score and seven', 2, 3, slice(6,10), 1)
['u', 'r', 'core', 'o']

You do have to use the explicit notation with built-in 'slice' rather than 
just the colon-notation for slice -- the latter is NOT accepted by Python 
(even Python 2.3) in general syntactic positions such as argument passing:

>>> getat('four score and seven', 2, 3, 6:10, 1)
  File "<stdin>", line 1
    getat('four score and seven', 2, 3, 6:10, 1)
                                         ^
SyntaxError: invalid syntax
>>>

But that's another issue -- if you want to argue for 6:10 as general
syntax sugar for slice(6:10), I guess you should do that on the python-dev 
mailing list where you might convince the BDFL (I suspect he'll veto it
once again as he did on all previous occasions, but, who knows).  If
you're serious about getting your suggested modification accepted, you
are well advised to write a PEP for it first.

Making blah[8,6] equivalent to [blah(x) for x in [8,6]] on the other
hand is clearly unacceptable because "blah[8,6]" already HAS a meaning,
and it is the same as blah[(8,6)].  Maybe that shouldn't be an error
when blah is a list -- i.e. maybe a sequence's __getitem__ should be
able to accept a sequence (in this case, a tuple) as well as an integer
or a slice -- but I have no indication that the BDFL is currently
prone to accepting further complications in the semantics of sequence
indexing.  Still, I don't claim to channel the BDFL (that's the
timbot's job, not mine), so, again, python-dev is where you might
possibly convince him (again, start by writing a PEP -- the bigger
the change you want, the more a PEP is needed -- ideally, a sample
patch wrt the current 2.3a0 CVS tree should also go with it, but
that's nowhere like mandatory except in cases where a mod's very
feasibility is in doubt).


Alex




More information about the Python-list mailing list