eval()
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 theexpression
‘s global scope. Ifglobals
isn’t specified,eval()
uses the current global scope.locals
(optional): A dictionary defining the variables in theexpression
‘s local scope. If thelocals
argument is specified, theglobals
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 thateval()
will have access to all of Python’s built-in names when evaluatingexpression
.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 = 10y = 5print(eval("x + y")) # Output: 15print(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:
All contributors
- Anonymous contributorAnonymous contributor2 total contributions
- StevenSwiniarski474 total contributions
- Anonymous contributor
- StevenSwiniarski
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.