Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python eval() Function

Python eval() Function

Python3 Built-in Functions Python3 built-in 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

- Type: string - Description: the Python expression to execute. - Type: dictionary - Description: the global namespace. - Type: dictionary - Description: the local namespace.

Function description


Example

Example 1: basic usage

Example

Evaluate a mathematical expression

result

=

eval

(

"1 + 2 + 3"

)

print

(

result

)

 

Output: 6

Using variables

x

=

10

result

=

eval

(

"x * 2"

)

print

(

result

)

 

Output: 20

A complex expression

result

=

eval

(

"2 ** 3 + 4 * 5"

)

print

(

result

)

 

Output: 28

Function call

result

=

eval

(

"len('hello')"

)

print

(

result

)

 

Output: 5

Expected output:

6
20
28
5

Code analysis:

  1. eval() It can execute arithmetic expressions.
  2. It can reference variables already defined.
  3. 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

)

print

(

result

)

 

Output: 30

Do not allow access to dangerous functions

try

:

   

eval

(

"import('os').system('ls')"

,

{

}

)

except

NameError

as

e:

   

print

(

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 Functions Python3 built-in function