Python exec() Function – Tutorial with Examples

The exec() function in Python is a built-in function that allows the execution of dynamically generated code. It takes a string argument, which is a piece of code, and executes it as if it were normal code. The exec() function can be useful in situations where you want to execute a piece of code that has been generated at runtime, such as reading code from a file or receiving it as user input.

Syntax

exec(object[, globals[, locals]])

Parameters

  • object – The string of code to be executed.
  • globals (optional) – A dictionary of global variables that will be available during the execution of the code. If not provided, the globals from the calling scope will be used.
  • locals (optional) – A dictionary of local variables that will be available during the execution of the code. If not provided, the locals from the calling scope will be used.

Return Value

The exec() function does not return a value. Instead, it executes the code and any changes made to variables during the execution will persist in the current scope.

Examples

Example 1: Basic Usage

code = "print('Hello, World!')"
exec(code)

Output:

Hello, World!

In this example, a string of code is defined and then passed to the exec() function. The code is executed and the message “Hello, World!” is printed to the console.

Example 2: Using Global Variables

code = "x = 10"
exec(code)
print(x)

Output:

10

In this example, a string of code is defined and executed using the exec() function. The code defines a global variable x with the value 10. The value of x is then printed after the execution of the code, demonstrating that the change made to the variable persisted in the current scope.

Example 3: Using Local Variables

code = "x = 10"
exec(code, {}, locals())
print(x)

Output:

NameError: name 'x' is not defined

In this example, a string of code is defined and executed using the exec() function with a dictionary of local variables passed as the third argument. The code defines a variable x with the value 10. However, the variable is not accessible in the current scope after the execution of the code, and a NameError is raised when trying to print its value. This demonstrates that the exec() function can be used to execute code in a separate scope with its own set of local variables, separate from the calling scope.

Use Cases

The exec() function can be useful in a variety of situations, such as:

  • Dynamic code execution, where the code to be executed is generated at runtime and not known beforehand.
  • Interactive programming, where the user can enter code to be executed on the fly.
  • Running code from external sources, such as reading code from a file or receiving it as user input.
  • Testing and debugging, where code can be executed and its behavior can be observed without modifying the main program.

It is important to note that the exec() function can be a security risk if used improperly. For example, if the code being executed is generated from untrusted sources, such as user input, it could potentially contain malicious code. Care must be taken to properly validate and sanitize the code before executing it with the exec() function.

In conclusion, the exec() function is a powerful tool for executing dynamically generated code in Python, but its usage should be carefully considered and thoroughly tested before being used in production code.

Leave a Reply

Your email address will not be published. Required fields are marked *