0%

🪄 The Code Within The Code

Runs Python code inside a string, like casting a spell on text. Want to run dynamic code on the fly? eval() makes it happen.
🔮 eval(“print(‘Conjuring…’)”)

A string is just text. Usually it sits there, silent and harmless. But sometimes you want that text to become alive. To transform from words into action. To speak as code. The eval() function is the whisper that brings text to life. It takes a string containing Python code and executes it as if you had written it yourself.

🕯️ 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.

The syntax eval(“print(‘Conjuring…’)”) tells Python to treat the string as a command. The print() function executes. The words appear. The string becomes a spell. You can also capture return values like result = eval(“2 + 3 * 4”) which stores 14 in result.
  • 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
💡 For evaluating safe mathematical expressions from trusted sources, eval() is convenient. For dynamic attribute access, use getattr() instead. For parsing JSON or simple data structures, use json.loads(). Only use eval() when you completely control the input and understand the risks.
Input Expressioneval() Result
“2 + 2”4
“len(‘hello’)”5
“max([1, 5, 3])”5
“‘magic’.upper()”“MAGIC”
“3 > 5”False
⚠️ Never use eval() with user input or untrusted strings. A malicious user could write __import__(‘os’).system(‘rm -rf /’) or access sensitive data. This is one of the most dangerous security vulnerabilities in Python. There is almost always a safer alternative: int(), float(), json.loads(), or custom parsers.
Examples

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

Common Mistakes
  • 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.