exec()

The built-in exec() function allows for the dynamic execution of Python code, which can be provided as either a string or a compiled code object. This function is powerful as it can execute full Python programs, but it should be used with caution due to potential security risks:

Python
>>> exec("print('Hello, World!')")
Hello, World!

exec() Signature

Python Syntax
exec(code, /, globals=None, locals=None, *, closure=None)

Arguments

Argument Description Default Value
code A string or a compiled code object containing valid Python statements -
globals A dictionary representing the global namespace for the execution context None
locals A mapping object representing the local namespace for the execution context None

Return Value

  • The exec() function returns None as its purpose is to execute code with potential side effects rather than produce a direct result.

exec() Examples

With a string containing Python code:

Python
>>> string_input = """
... def sum_of_even_squares(numbers):
...     return sum(number**2 for number in numbers if number % 2 == 0)
...
... print(sum_of_even_squares(numbers))
... """

>>> numbers = [2, 3, 7, 4, 8]
>>> exec(string_input)
84

With compiled code:

Python
>>> string_input = """
... def sum_of_even_squares(numbers):
...     return sum(number**2 for number in numbers if number % 2 == 0)
...
... print(sum_of_even_squares(numbers))
... """

>>> compiled_code = compile(string_input, "<string>", "exec")
>>> numbers = [2, 3, 7, 4, 8]
>>> exec(compiled_code)
84

exec() Common Use Cases

The most common use cases for the exec() function include the following:

  • Running dynamically generated Python code from strings or files
  • Implementing simple scripting capabilities within applications

exec() Real-World Example

Consider a situation where you need to execute configuration code from a file like the following:

Configuration File settings.conf
font_face = ""
font_size = 10
line_numbers = True
tab_size = 4
auto_indent = True

To generate and load a dictionary object with the application’s parameters, you can do the following:

Python
>>> from pathlib import Path
>>> def load_config(config_file):
...     config_file = Path(config_file)
...     code = compile(config_file.read_text(), config_file.name, "exec")
...     config_dict = {}
...     exec(code, {"__builtins__": {}}, config_dict)
...     return config_dict
...

>>> load_config("settings.conf")
{
    'font_face': '',
    'font_size': 10,
    'line_numbers': True,
    'tab_size': 4,
    'auto_indent': True
}

In this example, exec() helps load configuration settings stored in a file, updating a configuration dictionary with parameters used throughout an application.

Tutorial

Python's exec(): Execute Dynamically Generated Code

In this tutorial, you'll learn how to use Python's built-in exec() function to execute code that comes as either a string or a compiled code object.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 21, 2024 • Reviewed by Dan Bader