| title | Python exec() built-in function - Python Cheatsheet |
|---|---|
| description | This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs) [...]. |
The exec() function in Python is a built-in function that allows you to dynamically execute Python code stored in a string. This can be very powerful for scenarios where you want to execute code provided by users, generate and run code at runtime, or even build mini interpreters or scripting environments within your application. However, it should be used with caution as it can potentially introduce security risks if not handled properly.
exec(object[, globals[, locals]])object: The string containing the Python code to be executed.globals(optional): A dictionary representing the global namespace. If not provided, it uses the current global namespace.locals(optional): A dictionary representing the local namespace. If not provided, it uses the current local namespace.
code_to_execute = "print('Hello, exec()!')"
exec(code_to_execute)Hello, exec()!
The exec() function can also be used with the print() function to display output to the console.
code = """
for i in range(5):
print(i)
"""
exec(code)0
1
2
3
4
In this example, the exec() function is used to execute a for loop that iterates over a range of numbers and prints each number to the console.
x = 10
code = "x += 5"
exec(code)
print(x)15
x = 5
code = "x = x * 2"
globals_dict = {"x": 10}
locals_dict = {"x": 20}
exec(code, globals_dict, locals_dict)
print(x)
print(globals_dict)
print(locals_dict)5
{'x': 10}
{'x': 40}
def create_dynamic_function(name, args):
code = f"def {name}({', '.join(args)}): return sum({args})"
exec(code)
create_dynamic_function("add_numbers", ["a", "b", "c"])
result = add_numbers(2, 3, 5)
print(result)10
In this example, the exec() function is used to create a dynamic function that takes a list of arguments and returns their sum.
code = """
try:
print(undefined_variable)
except NameError as e:
print(f"Error: {e}")
"""
exec(code)Error: name 'undefined_variable' is not defined
user_input = input("Enter code to execute: ")
exec(user_input) # Caution: This can be a security risk if not properly sanitized.compile()eval()globals()locals()- Exception Handling
- Debugging