converting from perl: variable sized unpack

Alex Martelli aleaxit at yahoo.com
Mon Jul 16 08:12:52 EDT 2001


"Roy Smith" <roy at panix.com> wrote in message
news:roy-E01423.21425015072001 at news1.panix.com...
> quinn at yak.ugcs.caltech.edu (Quinn Dunkan) wrote:
> > Even without that, I argue that a bad pattern match should throw an
> > exception and not assign None
>
> I have to admit, that would be somewhat consistant with the way the rest
of
> the language works, but it sure would make it more complicated to do
> something like:
>
>    if re.match (pattern1, string):
>       do stuff
>    elif re.match (pattern2, string):
>       do other stuff
>    elif re.match (pattern3, string):
>       etc, etc, etc.

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.  If a failing re.match raised
ReException, and auxiliary functions dostuff &c were guaranteed
not to propagate ReException themselves, then...:
    try: dostuff(re1.match(thestring))
    except ReException:
        try: dootherstuff(re2.match(thestring))
        except ReException:
            try: etcetcetc(re3.match(thestring))
            except ReException: nomatchatall()
still a bit too 'nestful' for comfort, but better than the
current alternative IMHO.


Alex






More information about the Python-list mailing list