c enum - how to do this in python?

Alex Martelli aleax at aleax.it
Sat Feb 22 08:50:16 CET 2003


Anna wrote:

> On Fri, 21 Feb 2003 23:50:12 +0100, Rene Pijlman wrote:
> 
>> "yelims tluafed .p.l.c eht rof detanimoN"[::-1]
> 
> Seconded!
> 
> 'annA'[::-1]
> 
> --
> (Gee - I hope that's right... I can't run it in IDLE cuz I get an error
> that it's not integers... and I'd try from future import but I don't know
> what it's called...)

It's only in Python 2.3 (latest release, 2.3a2, the second alpha),
not in any version of 2.2 (not even with "from __future__ import").

Python 2.3 is not yet recommended for production use, being an
alpha release.  It does have a few neat things such as this one
(and sets and enumerate and itertools) and is faster than 2.2, so
for play/study purposes downloading it and installing it might be
fun, but be sure to keep a 2.2.2 around for "production use"!-)

"from __future__ import" is meant to introduce features gradually
when they BREAK the compatibility of some old code.  When that
is the case, then for at least one release cycle the old behavior
remains the default and you have to ask for the new one in this
explicit way.  But for additions that do not break existing code, there
is no need for the mechanism, so it's not used.

Reversing strings with [::-1] is more or less a divertissement, but
generalized slicing also has serious uses.  Say for example you want
to return the LAST item in a list that meets some condition.  With
generalized slicing in Python 2.3 it's easy:

def lastone(somelist, condition):
    for item in somelist[::-1]:
        if condition(item): return item
    raise ValueError, "No item matches the condition"

In Python 2.2 you need more a bit more work, e.g.:

def lastone1(somelist, condition):
    for i in range(len(somelist)-1, -1, -1):
        if condition(somelist[i]): return somelist[i]
    raise ValueError, "No item matches the condition"

or

def lastone1(somelist, condition):
    for i in range(len(somelist)):
        j = -i-1
        if condition(somelist[j]): return somelist[j]
    raise ValueError, "No item matches the condition"

or

def lastone(somelist, condition):
    revlist = somelist[:]
    revlist.reverse()
    for item in revlist:
        if condition(item): return item
    raise ValueError, "No item matches the condition"

etc, etc.  Nothing major, but not having "one obvious approach"
is not ideal.  Extended slicing helps...


Alex





More information about the Python-list mailing list