eval() is a built-in Python function that dynamically evaluates a string as a Python expression and returns the result — turning runtime strings into executable code. In 2026, eval() remains a powerful (but dangerous) tool for dynamic computation, configuration parsing, expression evaluation, and metaprogramming — especially useful in data science (dynamic filters/queries), interactive tools (Jupyter, REPLs), and DSLs (query languages, calculators). However, its security risks (arbitrary code execution) make safe usage critical; prefer ast.literal_eval() for constants or restricted environments for untrusted input.
Here’s a complete, practical guide to using eval() in Python: basic evaluation, globals/locals control, security & safe alternatives, real-world patterns (earthquake dynamic filtering, expression calculator, config parsing), and modern best practices with type hints, error handling, performance, and integration with Dask/Polars/pandas/xarray.
Basic eval() — evaluate expressions with current scope.
x = 10
y = 5
expr = "x * y + 3"
result = eval(expr)
print(result) # 53
# Function calls
def square(n): return n ** 2
print(eval("square(7)")) # 49
# List comprehensions & complex expressions
print(eval("[i**2 for i in range(5)]")) # [0, 1, 4, 9, 16]
Controlled evaluation — custom globals/locals for safety & isolation.
# Safe eval with restricted namespace
safe_globals = {"__builtins__": {}, "x": 10, "y": 5}
safe_locals = {}
result = eval("x * y", safe_globals, safe_locals)
print(result) # 50
# Trying dangerous code fails
try:
eval("import os; os.system('rm -rf /')", safe_globals)
except Exception as e:
print("Blocked:", e) # NameError or ImportError
Real-world pattern: dynamic earthquake filtering — user-defined expressions safely.
import pandas as pd
from ast import literal_eval
df = pd.read_csv('earthquakes.csv')
def safe_dynamic_filter(df: pd.DataFrame, user_expr: str) -> pd.DataFrame:
"""Safe eval for filtering with pandas context."""
try:
# Option 1: ast.literal_eval for constants (safest)
# mask = literal_eval(user_expr) # only literals
# Option 2: restricted eval with pandas locals
safe_globals = {"__builtins__": {}}
safe_locals = {"df": df}
mask = eval(user_expr, safe_globals, safe_locals)
return df[mask]
except Exception as e:
raise ValueError(f"Invalid filter expression: {user_expr}") from e
# Usage examples
filtered = safe_dynamic_filter(df, "df['mag'] >= 7.0")
print(filtered.shape)
filtered_deep = safe_dynamic_filter(df, "(df['mag'] >= 6.5) & (df['depth'] <= 70)")
print(filtered_deep.head())
# With variables
threshold = 6.0
filtered_var = safe_dynamic_filter(df, "df['mag'] >= threshold")
Best practices for eval() in Python & data workflows. Avoid eval() on untrusted input — massive security risk (code injection). Modern tip: prefer Polars pl.col('mag') >= 7.0 — safe & fast; use ast.literal_eval() for safe constants. Restrict namespaces — empty __builtins__ + controlled locals/globals. Use compile() first — for syntax checking before exec/eval. Add type hints — def safe_eval(expr: str, globals_: dict, locals_: dict) -> Any. Catch SyntaxError/NameError/TypeError — user-friendly messages. Use exec() — for statements (assignments); eval() for expressions only. Use ast.parse() — for safe analysis/transformation before eval. Use RestrictedPython — sandboxed eval for untrusted code. Use asteval — safer eval for scientific expressions. Profile performance — compile once, eval many times. Use eval() in REPLs — Jupyter, IPython. Use eval() in config — dynamic thresholds. Use eval() in DSLs — query languages, calculators. Avoid in production APIs — use safer parsers. Use ast.literal_eval() — for safe literals (numbers, strings, lists, dicts).
eval() executes dynamic Python expressions — powerful for flexible computation, but dangerous on untrusted input. In 2026, restrict namespaces, prefer Polars/Dask for data queries, use ast.literal_eval() for constants, and compile first for safety. Master eval(), and you’ll build dynamic, expressive tools while keeping security and performance in check.
Next time you need to run code from a string — use eval() carefully. It’s Python’s cleanest way to say: “Turn this text into live computation — but only when you trust it.”