eval()
Evaluates a string as a Python expression and returns the result. Powerful but dangerous with untrusted text: prefer ast.literal_eval().
eval(expression, globals=None, locals=None)eval() takes a string, treats it as Python code and returns the value of that code. eval("2 + 3 * 4") gives 14. It handles expressions only, things that produce a value; statements such as x = 5 or import are not allowed.
Safety warning: never pass text from users, files or the internet to eval(). The string can contain any Python code, including code that deletes files or reads secrets, and trying to block names does not make it safe. eval() is for strings your own program built.
To turn text such as "[1, 2, 3]" or "{'a': 1}" into real Python values, use ast.literal_eval(). It accepts only plain values (numbers, strings, lists, dicts, tuples, sets, True, False, None) and refuses everything else. To turn text into a number, use int() or float().
Parameters
| Parameter | What it is |
|---|---|
expressionrequired | A string holding one Python expression. |
globalsoptional, default None | A dictionary of names the expression can see. If you give it, only these names (plus the built-ins) are available. Pass it by position, as eval(text, names): the keyword form globals=names works only from Python 3.13. |
localsoptional, default None | A second dictionary of names, checked before globals. |
Return value
The value the expression produces.
Examples
1Evaluate a maths expression
print(eval("2 + 3 * 4"))
print(eval("(2 + 3) * 4"))
print(eval("10 / 4"))14 20 2.5
2Give the expression its own names
The second argument is a dictionary of the names the expression may use.
formula = "price * quantity * (1 - discount)"
values = {"price": 12.5, "quantity": 4, "discount": 0.1}
print(eval(formula, values))45.0
Here the formula comes from the program itself. If it came from a user, this would still not be safe.
3The safe way to read values: ast.literal_eval()
import ast
text = "[3, 1, 2]"
numbers = ast.literal_eval(text)
print(numbers, sum(numbers))
settings = ast.literal_eval("{'size': 12, 'bold': True}")
print(settings["size"])[3, 1, 2] 6 12
4literal_eval() refuses code
With eval() the last string would run and reach into the operating system. literal_eval() rejects it.
import ast
for text in ["42", "'hello'", "__import__('os').getcwd()"]:
try:
print(repr(ast.literal_eval(text)))
except ValueError:
print("Refused:", text)42
'hello'
Refused: __import__('os').getcwd()5Expressions only, not statements
try:
eval("total = 5")
except SyntaxError:
print("SyntaxError: eval() only takes expressions")
print(eval("5 > 3 and 'yes' or 'no'"))SyntaxError: eval() only takes expressions yes
Common mistakes
Using eval() to read numbers that users type
eval(input("Age: ")) lets the user run any code. Convert with int() or float(), which only accept numbers.
typed = "42"
age = int(typed)
print(age + 1)43
Thinking an empty __builtins__ makes eval() safe
eval(text, {"__builtins__": {}}) hides functions like open, but clever strings can still reach them through the attributes of ordinary objects. There is no reliable way to make eval() safe for untrusted text: use ast.literal_eval(), or write a small parser for the exact format you expect.
Questions people ask
Is eval() safe?
Only for strings your own program created. For anything from outside (user input, files, web requests) it is a serious security risk.
What is the difference between eval() and exec()?
eval() evaluates one expression and returns its value. exec() runs any statements, such as loops and assignments, and returns None. Both share the same safety problem.
How do I convert a string to a list in Python?
If the string looks like a list ("[1, 2, 3]"), use ast.literal_eval(). If it is values separated by commas ("1,2,3"), use str.split().
How do I build a simple calculator without eval()?
Split the input into number, operator, number and choose the operation with an if, or with a dictionary that maps "+" to a function from the operator module.