Serbin Serbin - 6 months ago 18
Python Question

Save value to global variable

How can I save some value to global variable?

There is a example script:

GLOBAL_VAR = None

def check_global_var(new_var):
global GLOBAL_VAR
if GLOBAL_VAR is None:
GLOBAR_VAR = new_var

print "In: " + str(GLOBAL_VAR)
check_global_var(True)
print "Out: " + str(GLOBAL_VAR)


I have a global variable
GLOBAL_VAR
with default value set to
None
. In function
check_global_var
I set this global variable to
True
. But the output is:

In: None
Out: None


But out should be
True
, since we set it in function.

Answer

There are typo in your script ( you assign to GLOBAR_VAR not to GLOBAL_VAR).

Update assignment from GLOBAR_VAR = new_var to GLOBAL_VAR = new_var and everything would work as expected.

Comments