0%

🪄 Some Codes Burn

exec() runs Python code inside a string, handling multiple lines and statements. It executes code but doesn’t return a value. You just see the effects.
🔮 exec(“x=3\ny=5\nprint(x+y)”)

Some spells return a result. A quick flash. A single value. But some spells do more. They change the world around them. They create variables. They define functions. They leave traces. The exec() function is the open flame. It takes a string of Python code and executes it. No return value. Just the effects of whatever the code does.

🕯️ Magic Note

Unlike eval() which works only on a single expression and returns a value, exec() can run any Python code: multiple lines, loops, conditionals, function definitions, class creations, and imports. The code runs in the current scope (or a provided one) and can modify it.

The syntax exec(“x=3\ny=5\nprint(x+y)”) contains three statements separated by newlines. First x=3 creates a variable. Then y=5 creates another. Finally print(x+y) shows the result. The code runs live. The effects are real.
  • Can run multiple lines, loops, conditionals, and function definitions
  • Returns None always, use side effects to see results
  • Use \n to separate lines inside a string
  • Accepts globals and locals dictionaries for controlled execution environments
💡 Use exec() for dynamic code generation, running user submitted scripts in a sandbox, or implementing plugins. Use eval() for evaluating single expressions that should return a value. Never use either with untrusted input without extreme sandboxing, which is almost impossible to do safely.
Featureeval()exec()
What it runsSingle expressionMultiple statements
Return valueThe expression resultNone
Can create variablesNoYes
Exampleeval(“3+5”) → 8exec(“x=3+5”) → None
Use caseCalculate from stringRun dynamic code blocks
⚠️ Like eval(), exec() is extremely dangerous with untrusted input. A malicious string can delete files, steal data, or compromise your system. Never use exec() on user input or data from external sources. There is almost always a safer design pattern.
Examples

Python

# Running multiple statements

code = “””

total = 0

for i in range(5):

total = total + i

print(total)

“””

exec(code)

# Output: 10

Python

# Creating variables dynamically

exec(“greeting = ‘Hello, conjurer'”)

print(greeting)

# Output: Hello, conjurer

Python

# Defining functions with exec

exec(“””

def double(x):

return x * 2

“””)

print(double(7))

# Output: 14

Common Mistakes
  • Expecting exec() to return a value, it always returns None
  • Using exec() where a simple function or loop would work, making code harder to debug
  • Running exec() on user input, creating a severe security vulnerability

⚡ Whisper

eval is a spark. Precise. Focused. Returning a single truth. exec is a fire. It spreads. It transforms. It leaves nothing unchanged. Both burn. Handle with silence and care.