Search code examples
pythonfunctionvariablesgloballocal

How do you make a string converted to a variable name instantiated inside of a function global?


Sorry for that confusing title, in my function my parameter is the name I want I want to set as a global variable name. I can do this outside of a function, and I can instantiate a global variable without a string as its name, and I haven't found any other articles with a solution to both problems at the same time.

def myFunc(varName):
    temp = varName
    # global vars()[temp]  <== This line produces the error
    vars()[temp] = 5  # varName becomes a local variable

Solution

  • You can use the globals function to achieve this:

    def set_global_var(name, value):
        globals()[name] = value
    
    
    if __name__ == '__main__':
        set_global_var('foo', 3)
        print(foo)
    

    Note that this is most of the case not a good idea. You might want to use a global dict object instead and simply assign new keys to it.