[CentralOH] Refactorio ad absurdum

jep200404 at columbus.rr.com jep200404 at columbus.rr.com
Thu Mar 12 01:39:18 CET 2015


dict.setdefault() seems non-Pythonic. I like it. :-)

On Tue, 10 Mar 2015 21:47:38 -0400, jep200404 at columbus.rr.com wrote:

> 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

Refactorio ad absurdum[1]:

    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:
            (parser[get_formula_type(line)])(line, (hoursdict.setdefault(get_hour(line), {})).setdefault(get_formula_type(line), {}))
        return hoursdict

It was fun to get the body of the loop down to one (very long 
non-PEP8) line. That is probably the hardest to understand 
Python code I have ever written. I wonder if it even runs. 
Can the original poster try it? Refactoring it to a 
dictionary comprehension probably would be interesting.
Using a map/reduce approach could also be fun and unreadable.

    def foo(lines):
        # Each parser function takes a single argument line, 
        # and returns a value for 
        # (hoursdict[get_hour(line)])[get_formula_type(line)].
        parser = {
            'MAXT': parse_h1h4_formulas,
            'MINT': parse_h1h4_formulas,
            'CLOUD': parse_cloud_formulas,
            'PRECIP': parse_precip_formulas,
        }

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

Hmmm, use dict.update() for reduce? 

Oh well, that's enough for today. Back on my head.

[1] wp:Reductio ad absurdum
    What is the valid latin for refactorio?


More information about the CentralOH mailing list