How can I assign the value of a variable using eval in python?
Because x=1
is a statement, not an expression. Use exec
to run statements.
>>> exec('x=1')
>>> x
1
By the way, there are many ways to avoid using exec
/eval
if all you need is a dynamic name to assign, e.g. you could use a dictionary, the setattr
function, or the :locals()
dictionary
>>> locals()['y'] = 1
>>> y
1
Update: Although the code above works in the REPL, it won't work inside a function. See Modifying locals in Python for some alternatives if exec
is out of question.
assign value to a variable using eval in a metaprogramming manner
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
Python - How can I assign a value to eval
counterc = 0
countern = 0
counterx = 0
letter = input()
if letter in ['c','n','x']:
globals()['counter{}'.format(letter)] += 1
print(globals()['counter{}'.format(letter)])
Thank me later
if you are using python2 input 'c' of you are on py3 just type c without quotes.
Python Newbie: using eval() to assign a value to a self.variable
eval
is a builtin not a default method for Python classes. But what you seek is setattr
:
def replaceByTwo(self, var_name):
setattr(self, var_name, 2)
Trial:
>>> t = trash()
>>> print(t.var2)
1
>>> t.replaceByTwo('var2')
>>> print(t.var2)
2
How to assign value to the output of eval function in python
Why don't you access your variables through globals()
(or locals()
) instead of eval
?
d={'a':10}
globals()['d']['a']=15
print d['a']
in your particular case
d={'a':10}
s1='d'
s2='a'
globals()[s1][s2]=15
print d['a']
Mass producing variables using eval - python
You could use exec
.
for i in range(100):
exec('number_{0} = {0}'.format(i))
Python: Assign and Eval string to number
You can give to eval a dictionary to use as global variables:
print(eval(formula, dict1))
Using Eval in Python to create class variables
You can use the setattr
function, which takes three arguments: the object, the name of the attribute, and it's value. For example,
setattr(self, 'wavelength', wavelength_val)
is equivalent to:
self.wavelength = wavelength_val
So you could do something like this:
for variable in self.variable_list:
var_type,var_text_ctrl,var_name = variable
if var_type == 'f' :
setattr(self, var_name, var_text_ctrl.GetValue())
eval() does not assign variable at runtime
Use exec
for statements:
>>> exec 'lis = [1,2,3]'
>>> lis
[1, 2, 3]
eval
works only on expressions, like 2*2
,4+5
etc
eval
and exec
are okay if the string is coming from a known source, but don't use them if the string is coming from an unknown source(user input).
Read : Be careful with exec and eval in Python
Related Topics
Python: Urllib2 How to Send Cookie with Urlopen Request
Python Script Execute Commands in Terminal
Django-Registration & Django-Profile, Using Your Own Custom Form
Attributeerror: 'List' Object Has No Attribute 'Click' - Selenium Webdriver
How to Create an SQL View with SQLalchemy
How to Make a Python Script Executable
Matplotlib - Add Colorbar to a Sequence of Line Plots
How to Load/Edit/Run/Save Text Files (.Py) into an Ipython Notebook Cell
How to Get Element-Wise Matrix Multiplication (Hadamard Product) in Numpy
Is Tensorflow Compatible with a Windows Workflow
How to Use Multiple Requests and Pass Items in Between Them in Scrapy Python
Iterate Over All Combinations of Values in Multiple Lists in Python
Using Django Database Layer Outside of Django
[] and {} VS List() and Dict(), Which Is Better
Most Efficient Way to Search the Last X Lines of a File