The exec()
function runs Python code from a string or a file, allowing for dynamic execution of multiple statements. It’s useful for running scripts, modifying variables dynamically, and executing external Python code.
Example
code = """
x = 10
y = 5
print(x + y)
"""
exec(code)
Output:
15
This executes multiple lines of code dynamically.
Syntax
exec(expression, globals=None, locals=None)
- expression → A string containing valid Python code.
- globals (optional) → A dictionary defining the global scope.
- locals (optional) → A dictionary defining the local scope.
1. Modifying Variables with exec()
You can dynamically update variables using exec()
.
x = 5
exec("x = x * 2")
print(x)
# Output: 10
Useful when working with dynamic configuration or variable modification.
2. Running a Function from a String
Define and execute a function from a string.
code = """
def greet(name):
return f'Hello, {name}!'
"""
exec(code)
print(greet("Alice"))
# Output: Hello, Alice!
Useful for dynamically generating functions.
3. Executing Code from a File
Run Python code directly from a file.
with open("script.py", "r") as file:
exec(file.read())
Great for loading external scripts dynamically.
4. Using exec()
with Restricted Scope
Limit variable access to prevent unwanted modifications.
safe_scope = {"x": 5}
exec("x = x + 10", safe_scope)
print(safe_scope["x"])
# Output: 15
This ensures code only modifies allowed variables.
Key Notes
- ✔ Runs multiple lines of Python code dynamically.
- ✔ Modifies variables and defines functions on the fly.
- ✔ Can execute external Python scripts.
- ✔ Use restricted scope (
globals
,locals
) for safety.
By using exec()
, you can execute Python code dynamically, making it a powerful tool for automation, scripting, and dynamic programming. 🚀