eval()
The built-in eval()
function allows you to dynamically evaluate Python expressions from a string or compiled code object and returns the result of the evaluated expression:
>>> eval("print('Hello, World!')")
Hello, World!
eval()
Signature
eval(expression, /, globals=None, locals=None)
Arguments
Argument | Description | Default Value |
---|---|---|
expression |
A string or a compiled code object representing a Python expression to evaluate | Required argument |
globals |
A dictionary representing the global namespace to use during evaluation | None |
locals |
A dictionary representing the local namespace to use during evaluation | None |
Note: If locals
is omitted, it defaults to globals
. If both arguments are omitted, then expression
is executed with the global and local name present in the environment where you called eval()
. These are possitional-only areguments.
Return Value
- The result and its date type depend on the evaluated expression.
eval()
Examples
With a mathematical expression as an argument:
>>> eval("2 + 2")
4
With a function call as an argument:
>>> eval("sum([1, 2, 3])")
6
With the globals
argument:
>>> x = 100 # A global variable
>>> eval("x + 100", {"x": x})
200
With the locals
argument:
>>> eval("x + 100", {}, {"x": 100})
200
eval()
Common Use Cases
The most common use cases for the eval()
function include the following:
- Evaluating mathematical expressions from user’s input or strings
- Dynamically calling functions based on string input
- Parsing and evaluating logical expressions
Note: Python’s eval()
has important security implications. It’s considered insecure because it may allows your users to dynamically execute arbitrary Python code. So, you should avoid using this function when you get the input expressions from an untrusted source.
eval()
Real-World Example
You can use eval()
to create an interactive command-line math expressions evaluator that processes and evaluates expressions provided by the user:
>>> def eval_expression(expression):
... code = compile(expression, "<string>", "eval")
... if code.co_names:
... raise NameError(f"Use of names not allowed")
... return eval(code, {"__builtins__": {}}, {})
...
>>> eval_expression("3 + 4 * 5 + 25 / 2")
35.5
>>> eval_expression("sum([1, 2, 3])")
Traceback (most recent call last):
...
NameError: Use of names not allowed
In this example, eval()
evaluates the user’s mathematical expression safely by restricting access to built-in functions, minimizing potential security risks.
Related Resources
Tutorial
Python eval(): Evaluate Expressions Dynamically
In this step-by-step tutorial, you'll learn how Python's eval() works and how to use it effectively in your programs. Additionally, you'll learn how to minimize the security risks associated to the use of eval().
For additional information on related topics, take a look at the following resources:
- Python's exec(): Execute Dynamically Generated Code (Tutorial)
- Python's Built-in Functions: A Complete Exploration (Tutorial)
- Namespaces and Scope in Python (Tutorial)
- How to Use Python Lambda Functions (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)
- Using Python Lambda Functions (Course)
- Python Lambda Functions (Quiz)