-2

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)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
misantroop
  • 2,276
  • 1
  • 16
  • 24
  • So what's the problem? If there's an error message, please include the whole thing. We shouldn't have to run the example just to see what the problem is. – wjandrea Apr 20 '20 at 13:09
  • The whole thing? eval fails with SyntaxError: invalid syntax – misantroop Apr 20 '20 at 13:13
  • 1
    Yes, edit the question to add the full error message with traceback. – wjandrea Apr 20 '20 at 13:19
  • 1
    You cannot put '=' in an eval statement. You'd have to do it in an exec: `exec('trueVal=%s' % (reference),globals(),locals())` – User 12692182 Apr 20 '20 at 13:23
  • Does this answer your question? [eval SyntaxError: invalid syntax in python](https://stackoverflow.com/questions/22558548/eval-syntaxerror-invalid-syntax-in-python) – wjandrea Apr 20 '20 at 13:24

2 Answers2

3

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

trueVal = eval(reference)
MatsLindh
  • 49,529
  • 4
  • 53
  • 84
  • Good, thanks. I also arrived at the result with a much more complicated and roundabout way of exec('x=reference', globals()) and exec('trueVal=eval(x)', globals()) – misantroop Apr 20 '20 at 13:22
2

I would not endorse using eval or exec, 99 times out of 100, there is a better way to do it, dictionary is not the only option but without posting your question its impossible to provide a better way to approach it. below is for reference as an example that works without hardcoding the variable name. But really there is always likely a better approach thatn eval or exec.

def func(reference, value):
    exec(reference + '="' + str(value) +'"')
    print(reference, ":", eval(reference))                 #Expecting trueVal=15000

trueValue = 15000
reference = 'trueVal'
func(reference, trueValue)
Chris Doyle
  • 10,703
  • 2
  • 23
  • 42