assignment expression peeve

Ben Finney bignose-hates-spam at and-benfinney-does-too.id.au
Wed Oct 15 00:54:27 EDT 2003


On 14 Oct 2003 21:12:29 -0700, Paul Rubin wrote:
> It gets annoying when there are 4 different regexps that the line
> might match, and I want to do something different depending on which
> one matches.

If you want to do lots of different things, you really should be placing
them in different functions:

    def deal_with_line_type_A():
        # do stuff for lines of type A

    def deal_with_line_type_B():
        # do stuff for lines of type B

This allows the tasks to be completely different for each type of line,
without cramming it into one structure.

Then, having defined what to do with each line type, map the regex to
the function for each type:

    line_action = {
        'AAA':  deal_with_line_type_A,
        'BBB':  deal_with_line_type_B,
    }

The dictionary then acts as the switchboard:

    for regex in line_action:
        match = re.match( regex, line )
        if( match ):
            line_action[regex](match)

Extending the range of lines is a matter of adding items to
line_actions, and writing the resulting function.  The decision code
remains the same.

-- 
 \           "Self-respect: The secure feeling that no one, as yet, is |
  `\                                 suspicious."  -- Henry L. Mencken |
_o__)                                                                  |
Ben Finney <http://bignose.squidly.org/>




More information about the Python-list mailing list