Python: good way to pass variable to multiple function calls
<p>Need a help with the next situation. I want to implement debug mode in my script through printing small completion report in functions with command executed name and ellapsed time like:</p>

<pre><code>def cmd_exec(cmd):
    if isDebug:
        commandStart = datetime.datetime.now()
        print commandStart
        print cmd
    ...
    ... exucuting commands
    ...
    if isDebug:
        print datetime.datetime.now() - command_start
    return

def main():
    ...
    if args.debug:
        isDebug = True
    ...
    cmd_exec(cmd1)
    ...
    cmd_exec(cmd2)
    ...
</code></pre>

<p>How can isDebug variable be simply passed to functions?
Should I use "global isDebug"? </p>

<p>Because </p>

<pre><code>    ...
    cmd_exec(cmd1, isDebug)
    ...
    cmd_exec(cmd2, isDebug)
    ...
</code></pre>

<p>looks pretty bad. Please help me find more elegant way.</p>

<p>Specifically for this, I would use partials/currying, basically pre-filling a variable.</p>

<pre><code>import sys
from functools import partial
import datetime

def _cmd_exec(cmd, isDebug=False):
    if isDebug:
        command_start = datetime.datetime.now()
        print command_start
        print cmd

    else:
        print 'isDebug is false' + cmd

    if isDebug:
        print datetime.datetime.now() - command_start
    return

#default, keeping it as is...
cmd_exec = _cmd_exec

#switch to debug
def debug_on():
    global cmd_exec

    #pre-apply the isDebug optional param
    cmd_exec = partial(_cmd_exec, isDebug=True)


def main():
    if "-d" in sys.argv:
        debug_on()

    cmd_exec("cmd1")
    cmd_exec("cmd2")

main()
</code></pre>

<p>In this case, I check for <code>-d</code> on the command line to turn on debug mode and I do pre-populate isDebug on the function call by creating a new function with <code>isDebug = True</code>.</p>

<p>I think even other modules will see this modified cmd_exec, because I replaced the function at the module level.</p>

<p>output:</p>

<p><strong>jluc@explore$ py test_so64.py</strong><br>
<code>isDebug is falsecmd1
isDebug is falsecmd2</code></p>

<p><strong>jluc@explore$ py test_so64.py -d</strong><br>
<code>2016-10-13 17:00:33.523016
cmd1
0:00:00.000682
2016-10-13 17:00:33.523715
cmd2
0:00:00.000009</code></p>

python function arguments global-variables