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:

Python
>>> eval("print('Hello, World!')")
Hello, World!

eval() Signature

Python Syntax
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

Return Value

  • The result and its date type depend on the evaluated expression.

eval() Examples

With a mathematical expression as an argument:

Python
>>> eval("2 + 2")
4

With a function call as an argument:

Python
>>> eval("sum([1, 2, 3])")
6

With the globals argument:

Python
>>> x = 100  # A global variable
>>> eval("x + 100", {"x": x})
200

With the locals argument:

Python
>>> 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

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:

Python
>>> 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.

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().

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 21, 2024 • Reviewed by Dan Bader