[CentralOH] Python Puzzler -- The little max bug: Refactor if/elif/elif, then whole mess

jep200404 at columbus.rr.com jep200404 at columbus.rr.com
Wed Mar 11 02:47:38 CET 2015


On Tue, 10 Mar 2015 19:38:48 -0400, Eric Floehr <eric at intellovations.com> wrote:

>     if formula_type in ('MAXT','MINT'):
>         parse_h1h4_formulas(f, hourdict[formula_type])
>     elif formula_type == 'CLOUD':
>         parse_cloud_formulas(f, hourdict[formula_type])
>     elif formula_type == 'PRECIP':
>         parse_precip_formulas(f, hourdict[formula_type])

That can be rearranged as:

    parser = {
        'MAXT': parse_h1h4_formulas,
        'MINT': parse_h1h4_formulas,
        'CLOUD': parse_cloud_formulas,
        'PRECIP': parse_precip_formulas,
    }

    for line in lines:

        ...

        (parser[formula_type])(line, hourdict[formula_type])

I don't know if the parentheses around parser[formula_type] 
are necessary.

-----------------------------------------------------------------

Refactoring the whole mess, yields:

    def foo(lines):
        parser = {
            'MAXT': parse_h1h4_formulas,
            'MINT': parse_h1h4_formulas,
            'CLOUD': parse_cloud_formulas,
            'PRECIP': parse_precip_formulas,
        }

        hoursdict = {}
        for line in lines:
            formula_type = get_formula_type(line)
            hour = get_hour(line)
            hourdict = hoursdict.setdefault(hour, {})
            hourdict[formula_type] = {}
            (parser[formula_type])(line, hourdict[formula_type])

        return hoursdict


More information about the CentralOH mailing list