Search⌘ K
AI Features

Exploring Dynamic Code and Safety

Explore the concepts of dynamic code execution in Python using eval and exec functions. Understand how to control execution scope with globals and locals, apply safe parsing with ast.literal_eval, and learn best practices to prevent security vulnerabilities when running dynamic code.

As the early days of computing, the ability for programs to modify and execute their own instructions introduced both flexibility and risk. In this lesson, we examine Python’s dynamic execution tools, which treat code as data. This capability supports tools such as custom REPLs, plugin systems, and dynamic template engines. However, these features must be used carefully because they can introduce significant security risks. If used improperly, these tools can introduce critical security vulnerabilities. It is therefore important to understand both how to use these features and how to apply them safely.

Evaluating expressions with eval()

The most common form of dynamic execution is evaluating a single expression. The eval() function parses a string containing a valid Python expression and returns the result. An expression is anything that evaluates to a value, such as mathematical operations, function calls, or list comprehensions.

Crucially, eval() can read variables from the current scope. If we have a variable defined in our code, the string passed to eval() can access it just as if the code were written directly in the file.

Python
x = 10
y = 5
# A string containing a Python expression
expression = "x * (y + 2)"
# Evaluating the string as code
result = eval(expression)
print(f"Expression: {expression}")
print(f"Result: {result}")
  • Lines 1–2: We establish the program state (x and y) that the dynamic code will need to access.

  • Line 5: We define the logic as a simple text string. At this stage, Python sees this only as characters, not as ...