Search code examples
pythonevalmetaprogramming

assign value to a variable using eval in a metaprogramming manner


I want to assign value to a variable using eval in a metaprogramming manner. My attempt was shown below:

sample = None
var_name = "sample"
value = 0
eval("{0} = {1}".format(var_name, value))

However, I got the following error:

Traceback (most recent call last):
  File "tmp.py", line 4, in <module>
    eval("{0} = {1}".format(var_name, value))
  File "<string>", line 1
    sample = 0
           ^
SyntaxError: invalid syntax

Could you explain how can I do this? I think lower level function like assign(var, val) could exist and this enabled assignment using eval. But I couldn't find such function.


Solution

  • Use exec instead:

    sample = None
    var_name = "sample"
    value = 0
    exec("{0} = {1}".format(var_name, value))
    

    eval is for evaluating an expression, not an assignment statement