Skip to content

Python eval vs exec

  • by

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()
PurposeEvaluates a single Python expressionExecutes a block of Python statements
InputString containing a Python expressionString or code object containing Python code
OutputReturns the result of the expressionNo return value
ExecutionExecutes a single expressionExecutes a block of code
Supported SyntaxValid Python expressionsValid Python code
Examplesresult = eval("2 + 3")exec("x = 2 + 3\nprint(x)")
Security RiskCan execute potentially harmful codeCan execute potentially harmful code
Error HandlingRaises an exception if an error occursRaises 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:

Python eval vs exec

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.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading