converting from perl: variable sized unpack

Roy Smith roy at panix.com
Mon Jul 16 15:30:13 CEST 2001


Alex Martelli <aleaxit at yahoo.com> wrote:
> I find I can rarely throw away the match-objects in this cavalier
> way, because they carry much, often-needed information -- so, I
> don't get to use this idiom anyway.  Rather, I have to code:
>
>    mo = re1.match(thestring)
>    if mo:
>        dostuff(mo)
>    else:
>        mo = re2.match(thestring)
>        if mo:
>            dootherstuff(mo)
>        else:
>            mo = re3.match(thestring)
>            if mo:
>                etcetcetc(mo)
>            else:
>                nomatchatall()
>
>which is hardly elegant and clean.

No it's not, but the problem is not that match returns None, the
problem is that Python doesn't allow assignment as a side effect.
Imagine if you could write it this way:

    if mo = re1.match(thestring)
        dostuff(mo)
    elif mo = re2.match(thestring)
        dootherstuff(mo)
    elif mo = re3.match(thestring)
        etcetcetc(mo)
    else:
        nomatchatall()

Wouldn't that be elegant and clean and obvious?

After 4 years of using Python, I still find the lack of any way to do
an atomic "assign and test" unbelievably constraining.




More information about the Python-list mailing list