eval(expression, globals=None, locals=None)

The eval() function evaluates the given expression and executes it as Python code.

Parameters

The eval() function accepts three parameters:

  • expression: Parses and executes the expression. Must be a string or a code object.
  • globals (optional): A dictionary representing the global namespace where the expression is executed. If provided and missing the __builtins__ attribute, the general global namespace is added before parsing, allowing access to all built-in modules.
  • locals (optional): A mapping object, typically a dictionary, representing the local namespace where the expression is executed. If not provided, the global namespace dictionary is used.

If neither globals nor locals are provided, the expression executes in the environment where the function call occurs. Raises SyntaxError on errors.

Return Value

  • Returns the result computed from the expression.

Examples

x = 1
eval('x + 1')  # 2

You can also use this function to execute arbitrary code objects, like those from compile. If the code object is in exec mode, None is returned.