The exec()
function enables execution of dynamically-generated code.
It takes one required argument, the object to be executed, this can be a string containing valid Python code or a code object generated by the builtin compile()
function.
exec(source, globals = None, locals = None)
copy
source |
A required argument representing the arbitrary Python code to be executed. It can be in form of a string or a code object generated by the builtin compile() function. |
globals |
Optional dictionary argument representing the global namespace that should be used for the execution |
locals |
Optional dictionary argument representing the local namespace that should be used for the execution |
The exec()
function executes the arbitrary Python object given in the source arguments. The function returns None
, this is unlike eva
l() which returns the results of the evaluation.
Example with strings
As shown above , we are passing the valid Python code as a python string. In the following example, we use a multi-line string.
Using compiled code object
The built-in compile() function is used to compile a Python code from a string, it returns a code object which can then be executed by passing it as an argument to the exec()
function.
In this approach, we first compiles the code snippet with compile()
then passes the returned code object to exec()
.
Passing the 'exec'
parameter as the third argument of the compile()
function tells the function that it should compile the snippet for execution by the exec()
function. This is important because the function is also used to compile code for other functions such as eval()
.
Note: you should be careful when using the exec()
function as it can potentially cause unintended consequences, such as security vulnerabilities. This is especially the case when you are executing the code from users or from external sources. In such cases, it is wise to ensure that you properly validate and sanitize the user’s input before executing it. This will ensure that any malicious code is not executed and thus help mitigate potential attack vectors.