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>For arbitrary code, the best you can do is write a function like</p>

<pre><code>def foo(file, f1, f2):
    with open(file) as input:
        for line in input:
            if 'REW' in line or 'LOSE' in line:
                f1(line)
                if 'REW VAL' in line or 'LOSE INV' in line:
                    f2(line)
</code></pre>

<p>where you need to impose some condition on how <code>f1</code> and <code>f2</code> are called (here, I define them as functions that take a line as input).</p>

<p>This isn't fully general, though. For instance, the function <code>f1</code> can't decide to skip the next <code>if</code> statement and continue to the next line from the file.</p>

python refactoring generator