Python 3 reference · Built-in Functions

Python eval() Function

Evaluate a single Python expression from a string and return its value. Dangerous with untrusted input.

Python 3 Since 3.0

Syntax

eval(source, /, globals=None, locals=None)

Parameters

ParameterDescription
source A string containing one expression, or a code object from compile().
globals optional A dictionary of global names the expression can see.
locals optional A mapping of local names.

Return value

The value of the expression.

Examples

Evaluate an expressionTry it yourself
print(eval("2 + 3 * 4"))
print(eval("x ** 2", {"x": 9}))

Output

14
81
The safe alternative for dataTry it yourself
import ast
# For data, ast.literal_eval() is safe: it only accepts literals
print(ast.literal_eval("[1, 2, {'a': True}]"))
try:
    ast.literal_eval("__import__('os').getcwd()")
except ValueError:
    print("rejected: not a literal")

Output

[1, 2, {'a': True}]
rejected: not a literal

Security

eval() runs arbitrary code. Never pass it text from users, files or the network; even restricted globals can be escaped. Parse data with ast.literal_eval(), json.loads() or int() / float() instead.

Version history

VersionChange
Python 3.0Added
Python 3.13globals and locals can be passed as keyword arguments.