I wonder if I can create a new variable and set it as a global variable.
Something like it this:
def f():
global new_global_var
if new_global_var is undefined:
new_global_var = None
print(new_global_var)
if __name__ == '__main__':
f()
print(new_global_var)
CodePudding user response:
This seems like something you really shouldn't be doing, but in any case, you can use globals()
here (which is essentially like a dictionary of global variables) to accomplish what you want:
def f():
if "hello" not in globals():
globals()["hello"] = 3
if __name__ == '__main__':
f()
print(hello)
CodePudding user response:
You can "try" to access the variable. If it does not exist, an exception will be raised. You will create the variable in the exception handler:
def f():
global new_global_var
try:
new_global_var
except NameError:
new_global_var = None