Switching off debug prints
<p>Sometimes I have a lot of prints scattered around function to print debug output.
To switch this debug outputs I came up with this:</p>

<pre><code>def f(debug=False): 
    print = __builtins__.print if debug else lambda *p: None
</code></pre>

<p>Or if I need to print something apart from debug message, I create <code>dprint</code> function for debug messages.</p>

<p>The problem is, when <code>debug=False</code>, this <code>print</code> statements slow down the code considerably, because <code>lambda *p: None</code> is still called, and function invocation are known to be slow.</p>

<p>So, my question is: Is there any better way to efficiently disable all these debug prints for them not to affect code performance?</p>

<hr>

<p>All the answers are regarding my not using <code>logging</code> module. This is a good to notice, but this <strong>doesn't answer the question</strong> how to avoid function invocations that slow down the code considerably - in my case 25 times (if it's possible (for example by tinkering with function code object to through away all the lines with <code>print</code> statements or somehow else)). What these answers suggest is replacing <code>print</code> with <code>logging.debug</code>, which should be even slower. And this question is about getting rid of those function calls completely.</p>

<p>I tried using <code>logging</code> instead of <code>lambda *p: None</code>, and no surprise, code became even slower.</p>

<hr>

<p>Maybe someone would like to see the code where those prints caused 25 slowdown: <a href="http://ideone.com/n5PGu" rel="nofollow">http://ideone.com/n5PGu</a></p>

<p>And I don't have anything against <code>logging</code> module. I think it's a good practice to always stick to robust solutions without some <a href="http://stackoverflow.com/a/12223240/862380"><em>hacks</em></a>. But I thinks there is nothing criminal if I used those <em>hacks</em> in 20-line one-time code snippet.</p>

<hr>

<p>Not as a restriction, but as a suggestion, maybe it's possible to delete some lines (e.g. starting with <code>print</code>) from function source code and recompile it? I laid out this approach in the answer below. Though I would like to see some comments on that solution, I welcome other approaches to solving this problem.</p>
