Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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.

expr = "[1, 2, 3]"
my_list = eval(expr)
my_list
[1, 2, 3]
eval("[1, 2, 3] * 2")
[1, 2, 3, 1, 2, 3]
import ast

expr = "[1, 2, 3]"
ast.literal_eval(expr)
[1, 2, 3]