Use exec() for Dynamic Code Generation in Python

Posted by Afsal on 20-Jun-2025
Hi Pythonistas!
Today I’m sharing one of Python’s most powerful and potentially risky tools: exec().
While you should use it cautiously, exec() can help you dynamically generate and execute code at runtime
useful in advanced tools, meta-programming, and code automation.
 
What Is exec()?
 
exec() runs any string as Python code, including full statements like defining functions, classes, or control flow.
code = """
def greet(name):
    print(f"Hello, {name}!")
"""
exec(code)

greet("Harry Potter ")
Output
Hello, Harry Potter!
You just created a function on the fly!
 
Real-Life Use Case: Dynamic Function Builder
>>> def make_adder(n):
...     code = f"""
... def add_{n}(x):
...     return x + {n}
... """
...     exec(code, globals())
... 

>>> make_adder(5)
>>> add_5(10)
15
>>> 
You’ve now generated a function named add_5 dynamically!
Warning: exec() Is Powerful and Dangerous
If you’re using user input, don’t trust it blindly:
user_code = input("Enter some Python code: ")

exec(user_code) # This can be dangerous
Instead, use this only when:
  • You trust the input
  • You’re writing internal tools
  • You need dynamic behavior that can’t be easily refactored
summary
  • exec() runs any Python code from a string
  • Great for code generation, advanced tools, and dynamic behavior
  • Avoid with untrusted input
In the upcoming for we will discuss some safer alternative for exec