Python eval() Function
eval() is a built-in Python function that executes a Python expression stored in a string.
eval() It takes a string, executes it as Python code, and returns the result. It is powerful but poses security risks if used improperly.
Word meaning: eval Is evaluateis short for (evaluate).
Basic syntax and parameters
Syntax format
eval(expression, globals, locals)
Parameter Description
- Parameter expression:
- Type: string
- Description: the Python expression to execute.
- Parameter globals(optional):
- Type: dictionary
- Description: the global namespace.
- Parameter locals(optional):
- Type: dictionary
- Description: the local namespace.
Function description
- Return Value: returns the result of the expression.
- Security Warning: do not use it on untrusted input
eval(), as it may lead to code injection attacks.
Example
Example 1: basic usage
Example
Evaluate a mathematical expression
result
=
eval
(
"1 + 2 + 3"
)
(
result
)
Output: 6
Using variables
x
=
10
result
=
eval
(
"x * 2"
)
(
result
)
Output: 20
A complex expression
result
=
eval
(
"2 ** 3 + 4 * 5"
)
(
result
)
Output: 28
Function call
result
=
eval
(
"len('hello')"
)
(
result
)
Output: 5
Expected output:
6
20
28
5
Code analysis:
eval()It can execute arithmetic expressions.- It can reference variables already defined.
- It can call built-in functions.
Example 2: restricted environment
Example
Restrict the available functions and variables
x
=
10
y
=
20
Create a restricted globals dictionary
safe_dict
=
{
"x"
: x
,
"y"
: y
,
"abs"
:
abs
}
result
=
eval
(
"x + y"
,
safe_dict
)
(
result
)
Output: 30
Do not allow access to dangerous functions
try
:
eval
(
"import('os').system('ls')"
,
{
}
)
except
NameError
as
e:
(
f
"Security restriction: {e}"
)
Expected output:
30
安全限制: name '__import__' is not defined
This example shows how to improve the security of eval() by restricting the globals dictionary.
Python3 built-in function