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.
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
2 Asked on December 30, 2021 by nitneuq
5 Asked on December 30, 2021 by sindre-sorhus
2 Asked on December 30, 2021
2 Asked on December 30, 2021 by jayjona
3 Asked on December 30, 2021 by shyam-nair
1 Asked on December 30, 2021
1 Asked on December 30, 2021 by i-shm
4 Asked on December 30, 2021 by learning-php
5 Asked on December 30, 2021 by ararat-harutyunyan
2 Asked on December 30, 2021
3 Asked on December 30, 2021 by antimonit
android android progressbar loading material components android progress bar
1 Asked on December 30, 2021 by mismas
0 Asked on December 30, 2021 by scar-fuentes
2 Asked on December 30, 2021 by ulugbek
0 Asked on December 30, 2021 by kanna
1 Asked on December 30, 2021
1 Asked on December 30, 2021
Get help from others!
Recent Questions
Recent Answers
© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir