Search code examples
pythonpython-3.xeval

Passing a string to eval in method


Struggling with passing a variable reference to a nested function. Using a dictionary is not an option in my use case. It's a much simplified MRE (real use passes an object with many nested objects).

def func(reference):
    eval('trueVal=' + reference)
    print(trueVal)                 #Expecting trueVal=15000

trueValue = 15000
reference = 'trueValue'
func(reference)

Solution

  • eval evaluates expressions. The result of your expression in your example can then be assigned to trueVal explicitly:

    trueVal = eval(reference)