🕯️ Magic Note
When you call eval(expression), Python parses the string, compiles it, and runs it as code. The result of that code becomes the return value of eval(). This works for any valid Python expression: calculations, function calls, string operations, and more.
- Works only with expressions, not full statements or assignments
- Can access variables currently in scope
- Accepts an optional globals and locals dictionary for controlled environments
- Use exec() for multi line statements or code blocks
| Input Expression | eval() Result |
|---|---|
| “2 + 2” | 4 |
| “len(‘hello’)” | 5 |
| “max([1, 5, 3])” | 5 |
| “‘magic’.upper()” | “MAGIC” |
| “3 > 5” | False |
Python
# Simple mathematical evaluation
expression = “15 * (3 + 2)”
result = eval(expression)
print(result)
# Output: 75
Python
# Working with variables in scope
x = 10
y = 5
operation = “x * y + x”
result = eval(operation)
print(result)
# Output: 60
Python
# Using eval with controlled globals
safe_dict = {“a”: 5, “b”: 3}
result = eval(“a * b”, safe_dict)
print(result)
# Output: 15
# Only a and b are accessible, not dangerous functions
- Using eval() on user input, creating a critical security vulnerability
- Trying to run statements or assignments like eval(“x = 5”) which raises a SyntaxError
- Assuming eval() is safe with restricted globals, Python objects can still escape via .__class__ chains
⚡ Whisper
Words can become actions. Text can transform into power. But with this magic comes great danger. The spell does not judge. It only executes. Choose your incantations wisely. Trust nothing that comes from the outside.