Python eval() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
Built-in

Definition

In Python, eval("2 + 3") parses the string as a Python expression, runs it, and returns its value, here 5. An expression is anything that produces a value: arithmetic, function calls, comprehensions. Statements such as assignments or loops are not allowed; that is what exec() is for.

By default the expression sees the caller's variables. You can pass your own globals and locals dictionaries to control which names it can use, but that only limits mistakes; it is not a security boundary.

eval() is a built-in function: it lives in the builtins module, so it is always available without an import.

Syntax

Pass a string (or a code object) and optional namespaces.

python
result = eval(expression)
result = eval(expression, globals_dict, locals_dict)
CallWhat it does
eval("2 + 3 * 4")Returns 14.
eval("x * 2")Uses the caller's variable x.
eval(expr, {"x": 3})Uses only the given names (plus built-ins).
ast.literal_eval("[1, 2]")The safe way to parse literals.

If you only need to turn text like "[1, 2, 3]" into a list, ast.literal_eval() does it safely.

Library declarations
python
eval(source, /, globals=None, locals=None)

Parameters

ParameterDescription
sourceRequired. A string with one expression, or a code object from compile().
globalsOptional. Dict of global names. If it lacks __builtins__, the built-ins are added automatically.
localsOptional. Mapping of local names. Defaults to globals.

Return Value

Return ValueDescription
anyThe value of the expression.

Python Examples

Example 1 — Evaluate Simple Expressions

Evaluate fixed strings with arithmetic, a function call, and a variable.

python
print(eval("2 + 3 * 4"))
print(eval("max([3, 9, 4])"))
print(eval("'py' * 3"))

x = 10
print(eval("x * 2"))

How It Works

  1. Normal precedence. The string is parsed like code, so multiplication happens first: 2 + 12.
  2. Built-ins available. max() works inside the expression.
  3. Any expression. String repetition is an expression too.
  4. Caller's variables. Without namespaces, the expression can read x from the surrounding code.

Example 2 — Evaluate a Formula with Chosen Names

Pass the formula's variables in a dict and remove the built-ins.

python
formula = "price * qty * (1 - discount)"
values = {"price": 20, "qty": 3, "discount": 0.25}

total = eval(formula, {"__builtins__": {}}, values)
print(total)

try:
    eval("len('abc')", {"__builtins__": {}})
except NameError:
    print("len is not available in this namespace")

How It Works

  1. Locals dict. The names in the formula are looked up in values.
  2. Float result. 20 × 3 × 0.75 is 45.0.
  3. No built-ins. An empty __builtins__ hides len(), so the second call raises NameError.
  4. Still not safe. Clever input can escape such restrictions; this only prevents accidents with trusted formulas.

Example 3 — ast.literal_eval() and Statement Errors

Parse a dict literal safely, see what literal_eval() rejects, and pass a statement to eval().

python
import ast

text = "{'name': 'Ana', 'scores': [90, 85], 'active': True}"
data = ast.literal_eval(text)
print(data["scores"][0], type(data).__name__)

for unsafe in ["__import__('os').getcwd()", "2 ** 10"]:
    try:
        ast.literal_eval(unsafe)
    except ValueError:
        print("literal_eval rejected:", unsafe)

try:
    eval("x = 5")
except SyntaxError:
    print("eval() accepts expressions only, not statements")

How It Works

  1. Literals only. ast.literal_eval() builds dicts, lists, strings, numbers, booleans, and None from text.
  2. No calls. Function calls, imports, and attribute access raise ValueError, so nothing can run.
  3. No operators either. Even 2 ** 10 is rejected; it is not a literal.
  4. Expressions only. eval("x = 5") raises SyntaxError; assignments need exec().

Frequently Asked Questions

It parses a string as a single expression, evaluates it, and returns the result.
Yes, with untrusted input. The string can run any code with your program's permissions. Never eval user input.
ast.literal_eval() for Python literals, json.loads() for JSON, and int() or float() for numbers.
eval() handles one expression and returns its value. exec() runs statements and always returns None.
No. It blocks simple mistakes, but there are known ways to escape it. Treat eval as unsafe for untrusted text.

Next: exec()

Execute a string of Python statements.

exec() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful