I am trying to write a python function with an optional argument tr, if this argument was not specified, then I want to take a global variable instead.
DEF_tARGET = "UserA"
def display_target(tr=DEF_TARGET):
print(tr)
The problem is that when I change the global variable somewhere in my program, then call the function with no tr argument, the function is still taking the initial value (when the function was declared) of the global variable. See the example below:
DEF_TARGET = "UserA"
def display_target(tr=DEF_TARGET):
print(f"target is {tr}")
display_target("UserB") # prints UserB
DEF_TARGET = "UserB"
display_target()
Output
target is UserA
Expected
target is UserB
I could declare the function as below, but I was looking for a better approach
def display_target(tr=None):
if not tr:
tr = DEF_TARGET
print(f"target is {tr}")
if not tr. Useif tr is None. Lots of things other thanNoneevaluate to false (False,0,"", etc.)if tr is Noneis the standard answer for global as default parametertr = tr or DEF_TARGET, which does the same.trisFalseor0or""or anything else that evaluates toFalse, you'll ignore it and useDEF_TARGETinstead. Change it totr = DEF_TARGET if tr is None else trif you want a one-line assignment.