In Python, eval()
and exec()
are built-in functions that allow you to execute dynamic code. Although they have similarities, they serve different purposes and have different implications. Here’s an overview of eval()
and exec()
:
eval()
Syntax:
eval(expression, globals=None, locals=None)
expression
: A string representing a Python expression to be evaluated.globals
(optional): A dictionary representing the global namespace. If provided, it will be used as the global variable while evaluating the expression.locals
(optional): A dictionary representing the local namespace. If provided, it will be used as the local variable while evaluating the expression.
exec()
Syntax:
exec(object, globals=None, locals=None)
object
: A string or code object representing a block of Python statements to be executed.globals
(optional): A dictionary representing the global namespace. If provided, it will be used as the global variables while executing the code.locals
(optional): A dictionary representing the local namespace. If provided, it will be used as the local variables while executing the code.
Here’s a tabular format comparing eval()
and exec()
in Python:
# | eval() | exec() |
---|---|---|
Purpose | Evaluates a single Python expression | Executes a block of Python statements |
Input | String containing a Python expression | String or code object containing Python code |
Output | Returns the result of the expression | No return value |
Execution | Executes a single expression | Executes a block of code |
Supported Syntax | Valid Python expressions | Valid Python code |
Examples | result = eval("2 + 3") | exec("x = 2 + 3\nprint(x)") |
Security Risk | Can execute potentially harmful code | Can execute potentially harmful code |
Error Handling | Raises an exception if an error occurs | Raises an exception if an error occurs |
Python eval vs exec example
Here are examples demonstrating the usage of eval()
and exec()
in Python:
eval()
example:
expression = "2 + 3"
result = eval(expression)
print(result) # Output: 5
exec()
example:
code = """
x = 2 + 3
print(x)
"""
exec(code)
Output:
It’s important to note that using eval()
and exec()
with untrusted or user-provided input can be dangerous. They can execute arbitrary code, leading to security vulnerabilities if not properly validated or sanitized. Caution should be exercised when using these functions, particularly in scenarios involving external input.
Do comment if you have any doubts or suggestions on this Python functions topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.