Search code examples
pythonpython-3.xglobal-variablesglobal

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

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