Yandex

Python exec() Function – Execute Dynamic Python Code



Python exec() Function

The exec() function in Python is used to execute dynamically created Python code. It takes a string as input and runs it as Python code.

This is a powerful tool, but it should be used carefully.

Syntax

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

Parameters:

  • object – A string or code object that will be executed as Python code.
  • globals – (Optional) A dictionary to specify the global namespace.
  • locals – (Optional) A dictionary to specify the local namespace.

Returns:

  • None – It executes the code but does not return anything.

Example 1: Basic Use of exec()

code = "x = 5\ny = 10\nprint('Sum:', x + y)"
exec(code)
Sum: 15

Example 2: Defining a Function Dynamically

func_code = '''
def greet(name):
    print("Hello, " + name)
'''
exec(func_code)
greet("Alice")
Hello, Alice

Use Case: Why Use exec()?

  • Running Python code stored in a string or file
  • Creating functions or variables dynamically
  • Useful in applications like templates, config interpreters, or code evaluators

Security Warning

Never use exec() with untrusted input! It can execute arbitrary code and pose a serious security risk.

Example 3: Using globals and locals

global_scope = {}
exec("x = 100", global_scope)
print(global_scope["x"])
100

Common Mistakes

  • Using exec() when eval() would be safer and simpler
  • Passing unvalidated or user input to exec()
  • Expecting a return value – exec() doesn't return the result of expressions

Interview Tip

exec() shows up in questions around code generation, sandboxing, or dynamic behavior. It's powerful but should be avoided in production unless absolutely necessary.

Summary

  • exec() executes Python code passed as a string or code object
  • Returns None, modifies scope directly
  • Use carefully – it can run any code

Practice Problem

Ask the user for a math expression and evaluate it using exec().

expr = input("Enter a Python statement (e.g., print(2+3)): ")
exec(expr)

Note: Use eval() if you're only evaluating expressions (not statements).



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M