What is exec()?

The exec() function in Python is a built-in function that allows the dynamic execution of Python program which is either a string or object code. It’s like you’re creating a program on the fly during the execution of your program and then running it.

Please note that exec() is a powerful function but it can be potentially dangerous if misused, as it can execute arbitrary Python code. Therefore, it should be used with caution, especially when executing user-supplied or untrusted input.

How to Use exec()?

The syntax of exec() is quite simple:

exec(object, globals, locals)
  • object: Required. Either a string, or an object. If it is an object, the object must be a code object.
  • globals: Optional. A dictionary containing global parameters.
  • locals: Optional. A dictionary containing local parameters.

If both dictionaries are omitted, the exec() function will execute in the current scope.

Allow and Block methods and variables

As I mentioned above, the exec() takes two optional dictionaries as arguments that define the global and local scope of the executed code. You can use these dictionaries to allow or prevent the usage of specific functions and variables inside exec().

Let’s say, for example, you want to allow the usage of the print() function and the variable x, but you want to prevent the usage of all other built-in functions and global variables. Here’s how you can do it:

# Define the allowed functions and variables
allowed_globals = {'print': print, 'x': 10}

# Try to use disallowed function and variable
code = """
y = x + 1
print(y)  # This is allowed
len('test')  # This is not allowed
"""

try:
    exec(code, allowed_globals)
except Exception as e:
    print(f"An error occurred: {e}")

In this example, the exec() function will raise a NameError when it tries to execute the len('test') line, because len is not defined in the allowed_globals dictionary.

If you want to prevent the usage of certain functions or variables, simply don’t include them in the dictionaries you pass to exec(). If you don’t pass any dictionaries at all, exec() will have access to all global variables and built-in functions.

Code Examples

Executing a simple statement:

# Executing a simple statement
exec('print("Hello, World!")')

Here, exec() is used to execute a simple print statement. The string passed to exec() is a valid Python statement which prints “Hello, World!” to the console when executed.

Executing a loop:

# Executing a loop
exec('for i in range(5): print(i)')

In this example, exec() is used to execute a for loop that prints numbers from 0 to 4. The string passed to exec() is a valid Python for loop.

Using exec() with globals and locals parameters:

# Using exec() with globals and locals parameters
x = 10
y = 2
exec('result = x ** y', {'x': x, 'y': y})
print(result)  # Prints: 100

Here, exec() is used to execute a Python expression that calculates the power of x to y. The second parameter to exec() is a dictionary that defines the global variables for the code being executed. In this case, it defines x and y to be 10 and 2 respectively. After exec() is called, the variable result contains the result of the expression x ** y.

Real-World Use Cases

  1. Dynamic code execution:
# User inputs a Python statement
user_code = input("Enter a Python statement: ")

# Execute the user-provided code
try:
    exec(user_code)
except Exception as e:
    print(f"An error occurred: {e}")

In this scenario, you’re creating a simple Python shell that takes in user input and executes it as Python code.

  1. Expression evaluators:
# User inputs an expression to evaluate
expression = input("Enter an expression: ")

# Evaluate the expression
try:
    exec(f"result = {expression}")
    print(result)
except Exception as e:
    print(f"An error occurred: {e}")

Here, you’re creating a simple calculator app where users can input their own formulas or expressions to evaluate.

  1. Custom scripting languages:

Suppose we have a custom scripting language where scripts are written like this: 'PRINT "Hello, World!"'. We could execute these scripts using exec() after converting them into Python code.

# A script in our custom scripting language
script = 'PRINT "Hello, World!"'

# Convert the script into Python code and execute it
python_code = script.replace('PRINT', 'print')
try:
    exec(python_code)
except Exception as e:
    print(f"An error occurred: {e}")

In this case, you’re converting a custom script into Python code by replacing the PRINT command with Python’s print() function, and then executing it.

Caution: Remember, exec() should be used sparingly and carefully, as it poses a serious security risk if you’re executing untrusted input. Always sanitize and check any input prior to executing it with exec() to prevent code injection attacks.

Similar Posts