converting from perl: variable sized unpack

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

"Roy Smith" <roy at> wrote in message
news:roy-E01423.21425015072001 at
> quinn at (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
> 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:
        mo = re2.match(thestring)
        if mo:
            mo = re3.match(thestring)
            if mo:

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.


More information about the Python-list mailing list