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:
>>> exec("print('Hello, World!')")
Hello, World!
exec()
Signature
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 returnsNone
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:
>>> 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:
>>> 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
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:
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:
>>> 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.
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Python eval(): Evaluate Expressions Dynamically (Tutorial)
- Python's Built-in Functions: A Complete Exploration (Tutorial)
- Namespaces and Scope in Python (Tutorial)
- Strings and Character Data in Python (Tutorial)
- Evaluate Expressions Dynamically With Python eval() (Course)
- Python's Built-in Functions: A Complete Exploration (Quiz)
- Navigating Namespaces and Scope in Python (Course)
- Namespaces and Scope in Python (Quiz)
- Strings and Character Data in Python (Course)
- Python Strings and Character Data (Quiz)