alternating control flow with conditionals or preprocessor
<p>Given this code:</p>

<pre><code>for i in range(5):
  foo(i)
  bar(i)
</code></pre>

<p>I want to add some code between the two <code>print</code> lines such that I can break the loop into two, but only if a certain flag is true, i.e.:</p>

<pre><code>for i in range(5):
  foo(i)

if debug: {
  continue
for i in range(5):
}

  bar(i)
</code></pre>

<p>Unfortunately this is not valid python. Is there a way I can do that without manually rewriting the loop to:</p>

<pre><code>if debug:
  for i in range(5):
    foo(i)
  for i in range(5):
    bar(i)
else:
  for i in range(5):
    foo(i)
    bar(i)
</code></pre>

<p>If I understand correctly, you want to either call functions in batches (all possible args for first function, then all possible args for second function etc) in first case, and arguments in batches in second case (so all function for first arg, then all functions for second arg etc.)</p>

<p>I'd say you have to do it explicitly:</p>

<pre><code>def foo(i):
    print("foo", i)

def bar(i):
    print("bar", i)

def stretch(seq, n):
    """stretch([1,2,3], 3) -&gt; [1,1,1,2,2,2,3,3,3], lazy generator"""
    for o in seq:
        for _ in range(n):
            yield o


def run(args, functions, mode):
    if mode:
        my_args = list(stretch(args, len(functions)))
        my_functions = functions * len(args)
    else:
        my_args = args * len(functions)
        my_functions = list(stretch(functions, len(args)))
    for f, a in zip(my_functions, my_args):
        f(a)
</code></pre>

<p>Invocation:</p>

<pre><code>run(list(range(5)), [foo, bar], 0)
</code></pre>

<p>Output:</p>

<pre><code>foo 0
foo 1
foo 2
foo 3
foo 4
bar 0
bar 1
bar 2
bar 3
bar 4
</code></pre>

<p>Invocation:</p>

<pre><code>run(list(range(5)), [foo, bar], 1)
</code></pre>

<p>Output:</p>

<pre><code>foo 0
bar 0
foo 1
bar 1
foo 2
bar 2
foo 3
bar 3
foo 4
bar 4
</code></pre>

<p>Here what we've done is that we created pairs for <code>(callable, argument_to_callable)</code> if order determined by your requirement. So essentially you have a boolean that "kind of" duplicated a loop for you.</p>

<p>Code is kind of ugly, I wonder if someone comes up with nicer solution.</p>

python