eval()

eval(expression, globals=None, locals=None)
Returns: any · Added in v3.0 · Updated March 13, 2026 · Built-in Functions
built-in execution dynamic expression security

The eval() function parses the expression argument as a Python expression, evaluates it in the specified global and local namespaces, and returns the result. It interprets the string as Python code, making it useful for dynamically evaluating expressions at runtime. However, executing arbitrary code from untrusted sources poses significant security risks.

Syntax

eval(expression, globals=None, locals=None)

Parameters

ParameterTypeDefaultDescription
expressionstrA string containing a valid Python expression
globalsdict or NoneNoneDictionary providing global variables accessible during evaluation
localsdict or NoneNoneDictionary providing local variables accessible during evaluation

Examples

Basic arithmetic evaluation

result = eval("2 + 3")
print(result)
# 5

result = eval("10 * 5 + 2")
print(result)
# 52

result = eval("(10 + 5) * 2")
print(result)
# 30

Using variables from globals

globals_dict = {"x": 10, "y": 5}
result = eval("x + y", globals_dict)
print(result)
# 15

result = eval("x ** 2", globals_dict)
print(result)
# 100

Combining globals and locals

globals_dict = {"width": 100}
locals_dict = {"height": 50}

result = eval("width * height", globals_dict, locals_dict)
print(result)
# 5000

Evaluating mathematical expressions

import math

result = eval("sin(pi/2)", {"sin": math.sin, "cos": math.cos, "pi": math.pi})
print(result)
# 1.0

result = eval("2 ** 10")
print(result)
# 1024

result = eval("round(3.7)")
print(result)
# 4

Safe evaluation with restricted globals

# Restrict available functions to math module only
safe_globals = {"__builtins__": {"math": __import__("math")}}

result = eval("math.sqrt(16)", safe_globals)
print(result)
# 4.0

# This would fail - not allowed:
# eval("__import__('os').system('rm -rf /')", safe_builtins)

Common Patterns

Building a simple calculator

def simple_calc(expression):
    """Evaluate a basic arithmetic expression safely."""
    allowed_chars = set("0123456789+-*/.() ")
    if any(c not in allowed_chars for c in expression):
        raise ValueError("Invalid characters in expression")
    return eval(expression)

print(simple_calc("2 + 3"))
# 5

print(simple_calc("(10 - 2) * 3"))
# 24

Evaluating user expressions in a game

def evaluate_move(formula, player_stats):
    """Evaluate a formula using player stats as context."""
    allowed = {k: v for k, v in player_stats.items() if isinstance(v, (int, float))}
    return eval(formula, {"__builtins__": {}}, allowed)

stats = {"attack": 10, "defense": 5, "multiplier": 2}
damage = evaluate_move("attack * multiplier", stats)
print(f"Damage: {damage}")
# Damage: 20

Security Warnings

Never use eval() on untrusted input. This is critical. When you pass user-supplied strings to eval(), you essentially give that user full access to execute arbitrary code on your system.

What a malicious user can do

# UNSAFE - Never do this!
user_input = input("Enter an expression: ")
result = eval(user_input)  # User can enter ANY Python code!

# A malicious user could enter:
# __import__('os').system('rm -rf /')
# Or worse - steal data, spawn processes, etc.

Mitigation strategies

  1. Never eval() user input directly — treat all user input as untrusted
  2. Use ast.literal_eval() — for safe evaluation of literals only
  3. Restrict globals/locals — pass empty dicts with minimal builtins
  4. Use sandboxes — consider process isolation for untrusted code
  5. Validate input first — whitelist allowed characters and patterns

Using ast.literal_eval instead

import ast

# Safe - only evaluates Python literals
result = ast.literal_eval("[1, 2, 3, 4, 5]")
print(result)
# [1, 2, 3, 4, 5]

result = ast.literal_eval("{'a': 1, 'b': 2}")
print(result)
# {'a': 1, 'b': 2}

result = ast.literal_eval("(1, 2, 3)")
print(result)
# (1, 2, 3)

# This is safe - won't execute code:
result = ast.literal_eval("__import__('os').system('ls')")
# ValueError: malformed node or string

Errors

ErrorWhen
SyntaxErrorExpression has invalid Python syntax
NameErrorExpression references an undefined name
TypeErrorWrong argument types passed to eval()
ZeroDivisionErrorExpression attempts division by zero
ValueErrorExpression evaluates to an invalid value

See Also