eval()

Anonymous contributor's avatar
Anonymous contributor
Anonymous contributor's avatar
Anonymous contributor
Published Aug 10, 2022Updated Aug 24, 2023
Contribute to Docs

The eval() function returns the value of a Python expression passed as a string.

Security Concerns

While eval() can be useful, care must be taken to understand the security implications of this function. If eval() is used with user-generated strings, a malicious user could execute arbitrary code through the function. Good programming practice generally advises against using eval(). If it is used, it should never be used with untrusted input.

Syntax

eval(expression, globals, locals)

The eval() function uses the following parameters:

  • expression: The expression to evaluate.
  • globals (optional): A dictionary defining which variables are in the expression‘s global scope. If globals isn’t specified, eval() uses the current global scope.
  • locals (optional): A dictionary defining the variables in the expression‘s local scope. If the locals argument is specified, the globals argument must be specified as well.

Note: While using the globals argument overrides the user defined variables available, if it doesn’t specify a value for the __builtins__ key, then a reference for it is automatically added so that eval() will have access to all of Python’s built-in names when evaluating expression.

Note: eval() does not support keyword arguments and it doesn’t work on compound statements or assignment operations. It only works with expressions that can be evaluated to be equal to some value.

Example

The following example uses eval() to evaluate an expression using variables in the current global scope, then evaluates the same expression with its own global scope:

x = 10
y = 5
print(eval("x + y")) # Output: 15
print(eval("x + y", {"x":15, "y":y})) # Output: 20

Codebyte Example

In the examples below, the eval() function is used to return a value from a string:

us
Visit us
code
Hide code
Code
Output
Hide output
Hide output
Loading...

All contributors

Looking to contribute?

Learn Python on Codecademy