'Can I create global variable in fuction scope in Python?

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)



Solution 1:[1]

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)

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mustafa Quraish
Solution 2 DYZ