Vadim  K Vadim K - 1 month ago 6
Python Question

Python: good way to pass variable to multiple function calls

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:

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)
...


How can isDebug variable be simply passed to functions?
Should I use "global isDebug"?

Because

...
cmd_exec(cmd1, isDebug)
...
cmd_exec(cmd2, isDebug)
...


looks pretty bad. Please help me find more elegant way.

Answer

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.

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

my_debug.py:

isDebug = false

main.py:

import my_debug

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

def main():
    # ...
    if args.debug:
        my_debug.isDebug = True
Comments