assignment expression peeve

Mark Day mday at apple.com
Wed Oct 15 13:18:10 EDT 2003


In article <7x1xtfkuky.fsf at ruckus.brouhaha.com>, Paul Rubin
<http://phr.cx@NOSPAM.invalid> wrote:

> Without assigment expressions, it gets unspeakably ugly.  You have to
> use a deeply nested if/else if sequence where you match the regexp and
> test the result on 2 separate lines at each branch, or reorganize the
> code to use some kind of dispatch table (good if there's a lot more
> than 4 regexps, but overkill for just 4), or whatever.

If you want to address the nesting aspect of the problem, don't forget
the continue and break statements.  Instead of needing a (nested) else
clause, you can put a continue or break in the if clause, and put the
"else" work at the same indentation as the "if" statement itself.  For
example:

    for line in file:
        g = re.match(pat1, line)
        if g:
            croggle(g.group(1), 17)
            continue

        g = re.match(pat2, line)
        if g:
            x = mugwump(g.group(3))
            y = wumpus(g.group(2))
            return defenestrate(x, y+3)

        g = re.match(pat3, line)
        if g:
            # do something completely different with groups of g
            continue

        g = re.match(pat4, line)
        if g:
            # more of the same
            continue

Note that the match against pat2 already does a return, so no continue
needed.

-Mark




More information about the Python-list mailing list