Search code examples
pythonargumentsglobal-variables

Python: modify global var from a function argument


I'd like to create a function that will modify an initialized global variable based on the argument passed to it, but I get a SyntaxError: name 'arg' is local and global. I have seen other methods to accomplish this, using globals() or creating a simple func inside myFunc to "trick" Python. Another approach would be to create if statements inside myFunc to explicitly assign the corresponding global variables, but that seems overly verbose.

Why does this occur, and what would be the most efficient/elegant/Pythonic way to accomplish this?

Given:

var1 = 1
var2 = 2
var3 = 3

def myFunc(arg):
    global arg
    arg = 10

myFunc(var1) # each of these should print to 10
myFunc(var2)
myFunc(var3)

Solution

  • You can use globals() to access the variables and assign new values from within myFunc()

    var1 = 1
    var2 = 2
    
    def myFunc(varname):
        globals()[varname] = 10
    
    print(var1, var2)
    
    myFunc("var1")
    myFunc("var2")
    
    print(var1, var2)
    

    Will output:

    1, 2
    10, 10