0
0
PythonHow-ToBeginner · 3 min read

How to Use exec Function in Python: Syntax and Examples

The exec function in Python runs dynamically created Python code given as a string. It can execute statements like assignments, loops, or function definitions within the current scope.
📐

Syntax

The exec function takes a string containing Python code and executes it. Optionally, you can provide dictionaries for global and local variables to control the execution environment.

  • exec(object, globals=None, locals=None)
  • object: A string of Python code to execute.
  • globals: Optional dictionary to specify global variables.
  • locals: Optional dictionary to specify local variables.
python
exec(object, globals=None, locals=None)
💻

Example

This example shows how to use exec to define a variable and a function dynamically, then call the function.

python
code = '''
result = 0
def add(a, b):
    return a + b
result = add(5, 7)
'''
exec(code)
print(result)
Output
12
⚠️

Common Pitfalls

Using exec can be risky because it runs any code, which may cause security issues if the input is not trusted. Also, variables created inside exec may not appear in the current scope unless you manage the globals and locals dictionaries properly.

Wrong way (variables not accessible):

python
code = 'x = 10'
exec(code)
try:
    print(x)
except NameError:
    print('x is not defined')

# Right way with globals:
globals_dict = {}
exec(code, globals_dict)
print(globals_dict['x'])
Output
x is not defined 10
📊

Quick Reference

Remember these tips when using exec:

  • Use exec to run dynamic Python code strings.
  • Pass globals and locals dictionaries to control variable scope.
  • Avoid using exec on untrusted input to prevent security risks.
  • Variables created inside exec may not be accessible outside without proper scope management.

Key Takeaways

Use exec to run Python code stored as strings dynamically.
Always manage globals and locals to control variable scope.
Never run exec on untrusted input to avoid security risks.
Variables created inside exec may not be accessible outside without proper dictionaries.
Use exec carefully as it can execute any Python code.