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>You can use a module to create variables that are shared. This is better than a global because it only affects code that is specifically looking for the variable, it doesn't pollute the global namespace. It also lets you define something without your main module needing to know about it.</p>

<p>This works because modules are shared objects in Python. Every <code>import</code> gets back a reference to the same object, and modifications to the contents of that module get shared immediately, just like a global would.</p>

<p>my_debug.py:</p>

<pre><code>isDebug = false
</code></pre>

<p>main.py:</p>

<pre><code>import my_debug

def cmd_exec(cmd):
    if my_debug.isDebug:
        # ...

def main():
    # ...
    if args.debug:
        my_debug.isDebug = True
</code></pre>

python function arguments global-variables