Welcome to Day 37 of your Python journey!
Today we’re discussing a very powerful but potentially dangerous function: eval()
.
Let’s learn:
- What
eval()
does - Why it can be risky
- And most importantly — how to use it safely (or avoid it)
🧠 What is eval()
?
eval()
evaluates a string as a Python expression and returns the result.
Example:
result = eval("3 + 5")
print(result) # Output: 8
It’s like turning a string into live Python code. Powerful, right? But that’s also what makes it risky. 🧨
🚨 Why eval()
is Dangerous
If you allow users to input code, eval()
can execute malicious commands.
Dangerous Example:
user_input = "__import__('os').system('rm -rf /')"
eval(user_input) # 😱 Can delete your entire system!
Even something innocent-looking like eval("open('secret.txt').read()")
can leak private files.
✅ When to Use eval()
(if ever)
Use eval()
only if:
- You fully control the input (no user interaction).
- You really need dynamic evaluation.
Still, prefer safer alternatives.
🔐 Safer Alternatives
1. ast.literal_eval()
(Best Alternative)
Safely evaluates literals (strings, numbers, lists, dicts).
import ast
expr = "{'name': 'Alice', 'age': 30}"
safe_result = ast.literal_eval(expr)
print(safe_result) # {'name': 'Alice', 'age': 30}
This won't execute functions or import modules. ✅
2. Use JSON
For structured data, prefer JSON.
import json
data = json.loads('{"a": 10, "b": 20}')
print(data)
⚙️ Restricted eval()
with Globals and Locals
You can limit access by passing restricted dictionaries:
safe_globals = {"__builtins__": None}
safe_locals = {"x": 10, "y": 5}
expr = "x + y"
result = eval(expr, safe_globals, safe_locals)
print(result) # Output: 15
Still, this should be your last resort — not a go-to solution.
🛠️ Use Cases (When It's Justified)
- Tiny calculators or math evaluators (with sandboxing)
- Dynamic expression evaluation in controlled internal tools
- Data science notebooks with fully trusted inputs
🔄 Summary
Feature | Use When | Safer Alternative |
---|---|---|
eval() |
You control the input | ast.literal_eval() |
User input eval | Never (unless sandboxed) | JSON or ast parsing |
Complex logic | Avoid or sandbox properly | Use logic in functions |
✅ TL;DR
-
eval()
executes Python code from strings — powerful but dangerous. - Never use it on untrusted input.
- Prefer
ast.literal_eval()
orjson
for safe parsing. - Restrict scope with
globals
andlocals
if you must use it.