Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I assign the value of a variable using eval in python?

Tags:

python

Okay. So my question is simple: How can I assign the value of a variable using eval in Python? I tried eval('x = 1') but that won't work. It returns a SyntaxError. Why won't this work?

like image 680
tew Avatar asked Apr 08 '11 18:04

tew


People also ask

Can we use eval as variable in Python?

You can use the built-in Python eval() to dynamically evaluate expressions from a string-based or compiled-code-based input. If you pass in a string to eval() , then the function parses it, compiles it to bytecode, and evaluates it as a Python expression.

How do you assign a value to a variable in Python?

The assignment operator, denoted by the “=” symbol, is the operator that is used to assign values to variables in Python. The line x=1 takes the known value, 1, and assigns that value to the variable with name “x”. After executing this line, this number will be stored into this variable.

What does eval () do in Python?

Answer: eval is a built-in- function used in python, eval function parses the expression argument and evaluates it as a python expression. In simple words, the eval function evaluates the “String” like a python expression and returns the result as an integer.

What is the use of eval () explain with an example?

In this program, expression can have sqrt() method and variable a only. All other methods and variables are unavailable. Restricting the use of eval() by passing globals and locals dictionaries will make your code secure particularly when you are using input provided by the user to the eval() method.


2 Answers

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.

like image 147
kennytm Avatar answered Oct 10 '22 23:10

kennytm


You can't, since variable assignment is a statement, not an expression, and eval can only eval expressions. Use exec instead.

Better yet, don't use either and tell us what you're really trying to do so that we can come up with a safe and sane solution.

like image 34
Rafe Kettler Avatar answered Oct 10 '22 23:10

Rafe Kettler