← All languages
Python function of the day
Random

eval

Evaluate a Python expression from a string-based or compiled-code-based input.

Description

The eval() function evaluates a Python expression from a string or compiled code object and returns the result. The expression is parsed and evaluated as a Python expression using the globals and locals dictionaries as the global and local namespace.

If the globals dictionary is provided without a __builtins__ key, the current builtins are automatically inserted before the expression is parsed. The locals dictionary defaults to the globals dictionary if not provided.

Caution should be exercised when using eval() with untrusted input, as it can execute arbitrary Python code. For safer alternatives, consider using ast.literal_eval() for evaluating literal expressions or restricting the available globals and locals.

Arguments

NameDescriptionOptional
expression A string or compiled code object to evaluate. No
globals A dictionary to use as the global namespace. Yes
locals A mapping to use as the local namespace. Yes

Example

eval('2 + 3')  # Returns 5
x = 10
eval('x * 2')  # Returns 20

Reference