Ben Chuanlong Du's Blog

And let it direct your passion with reason.

The eval Function in Python

The function eval takes a single line of code as string, evaluates it, and returns the value. Notice that objects in the evaluated expression must be present in the current scope, otherwise, exceptions will be thrown.

Even though eval (together with exec) might be useful in some situations, e.g., when implementing a REPL. It is strongly suggested that you avoid using eval in your Python code. Notice that some use cases of eval can be replaced with getattr.

In [3]:
expr = "[1, 2, 3]"
my_list = eval(expr)
my_list
Out[3]:
[1, 2, 3]
In [6]:
eval("[1, 2, 3] * 2")
Out[6]:
[1, 2, 3, 1, 2, 3]
In [9]:
import ast

expr = "[1, 2, 3]"
ast.literal_eval(expr)
Out[9]:
[1, 2, 3]
In [ ]:
 

Comments