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>Preprocessor derivatives change your code before it ever gets to run. In the C family of languages, for example, the compiler substitutes all expressions within <a href="https://en.wikipedia.org/wiki/C_preprocessor" rel="nofollow">preprocessor</a> blocks before compilation.</p>

<p>In your example, <code>debug</code> is a runtime variable, so there is no way you could change the structure of your code based on that variable. At least not in Python anyway.</p>

<p>However, there is <strong>always</strong> (well, almost always) a way you can avoid doing something manually. 
In the same spirit of true preprocessor blocks changing the code before it gets to run, we have to go a level up and add in content before the code gets executed.
The simplest way to do that is to manipulate your code as a string, and modify the string on the run.
I won't stress enough how unpythonic this contrived example is, but using <code>exec</code> you can inject the code you want. The solution will always work, no matter what function you use. Here it goes:</p>

<p>First, define your debug flag</p>

<pre><code>if_debug = ""
if debug:
    if_debug = "continue\nfor i in range(5):\n    "
</code></pre>

<p>Finally, wrap your code within a <code>exec("")</code> block. The string substitution happens before the code is sent to the interpreter for evaluation.</p>

<pre><code>exec("""
for i in range(5):\n
    foo(i)\n    """
+ if_debug + 
   "bar(i)")
</code></pre>

<p>There are macro libraries that allow you to change the way your code gets interpreted. Have a look at <a href="https://github.com/lihaoyi/macropy" rel="nofollow">MacroPy</a>, for example.</p>

python