TransWikia.com

assign value to a variable using eval in a metaprogramming manner

Stack Overflow Asked by orematasaburo on October 16, 2020

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.

3 Answers

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

Correct answer by GProst on October 16, 2020

If you're outside a function you can use

globals()[varname] = value

Example:

>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> globals()['a'] = 5
>>> a
5

Inside a function there's locals() but it can only read from the symbol table and not update so you should use eval() like other answers have pointed out.

You can also cheat by using setattr/hasattr/getattr on an object:

>>> class Object:
...     pass
... 
>>> obj = Object()
>>> obj.a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Object' object has no attribute 'a'
>>> setattr(obj, 'a', 3)
>>> obj.a
3

Answered by kouta-kun on October 16, 2020

does exec accomplish what you're trying to do?:

sample = None
var_name = "sample"
value = 5
exec(f"{var_name} = {value}")

print(sample)

output: 5

Answered by Ironkey on October 16, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP