Skip to content

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:

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

exec() Signature

Language: 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:

Language: 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:

Language: 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:

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

Note: The exec() function is a powerful tool that allows you to execute arbitrary Python code that comes to you as strings. You should use exec() with extreme care and caution, especially in those cases where the code comes from untrusted sources.

exec() Real-World Example

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

Language: Configuration File Filename: 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:

Language: 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.

Python's exec(): Execute Dynamically Generated Code

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 June 20, 2026 • Reviewed by Dan Bader
Morty Proxy This is a proxified and sanitized view of the page, visit original site.