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
| Parameter | Description |
|---|---|
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
print(eval("2 + 3 * 4"))
print(eval("x ** 2", {"x": 9}))
Output
14 81
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 literalSecurity
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
| Version | Change |
|---|---|
| Python 3.0 | Added |
| Python 3.13 | globals and locals can be passed as keyword arguments. |