Search code examples
pythondynamiclocal-variableskeyword-argument

Dynamically set variables inside function


There is some old script I am trying to use, but with different parameters than the ones that are currently hard-coded.

I thought about putting the code into a function and dynamically set the variables inside.

def run_test(**kwargs):
    print(locals())
    locals().update(kwargs)
    print(locals())
    print(a)

So I update the local variable with all the values that were passed as key word arguments.

However I get an error if I pass a as a key word.

run_test(a=2, b=3)

It is a NameError, a is not defined.

I don't get it. "a" gets added to locals inside the function but it can't be called. It works with globals, but why doesn't it work with locals?


Solution

  • You need to use eval() function to correctly access local variable inside the function:

    def run_test(**kwargs):
        print(locals())
        locals().update(kwargs)
        print(locals())
        print(eval("a"))
    
    
    run_test(a=2, b=3)
    

    Output:

    {'kwargs': {'a': 2, 'b': 3}}
    {'kwargs': {'a': 2, 'b': 3}, 'a': 2, 'b': 3}
    2