A generator for refactoring a combination of for loops and nested if statements
<p>The next code scans some log file and selects the lines with some particular characters.</p>

<pre><code>with open(file) as input:
    for line in input:
        if 'REW' in line or 'LOSE' in line:
            &lt;some optional code&gt;
            if 'REW VAL' in line or 'LOSE INV' in line:
                &lt;some code&gt;
</code></pre>

<p>I wrote some functions upon this but every function contains this repeated code, so I think refactoring is needed. And I guess I need to make a generator. How do I make this generator that will allow me to change the code in brackets?</p>

<p>Sometimes repetition is not that bad!</p>

<p>But anyway you can try something like this:</p>

<pre><code>#!/usr/bin/env python
# script.py

def process_file(filename, func1, func2):
    with open(filename) as f:
        for line in f:
            if '1' in line:
                func1(line)
                if '2' in line:
                    func2(line)


def main():
    counters = {1: 0, 2: 0}
    def func1(line):
        # TODO Add some logic based on line value here
        counters[1] += 1
    def func2(line):
        counters[2] += 1
    process_file('table.csv', func1, func2)
    return counters


if __name__ == '__main__':
    print(main())
</code></pre>

<p>And if you have a file:</p>

<pre><code>$ cat table.csv
1 just one
1 2 one and two
1
1
0
0
2
2 1
1 0 2
0
</code></pre>

<p>And run the script:</p>

<pre><code>python script.py
</code></pre>

<p>You will get the next output:</p>

<pre><code>{1: 6, 2: 3}
</code></pre>

<p>Also you can factor out predicates of your <code>if</code> statements:</p>

<pre><code>def process_file(filename, func1, func2, predicate1, predicate2):
    with open(filename) as f:
        for line in f:
            if predicate1(line):
                func1(line)
                if predicate2(line):
                    func2(line)

def predicate1(line):
    return 'REW' in line or 'LOSE' in line
</code></pre>

<p>Don't forget to choose nice function names!</p>

python refactoring generator