Python eval() Function

Python3 内置函数Python3 Built-in Functions


eval()Is a built-in function in Python used to execute Python expressions in strings.

eval()Accepts a string, executes it as Python code, and returns the execution result. It is a powerful feature, but improper use can bring security risks.

Word Definition: evalYesevaluateAbbreviation of (evaluation).


Basic Syntax and Parameters

Syntax Format

eval(expression, globals, locals)

Parameter Description

  • Parameter expression:
    • Type: String
    • Description: The Python expression to be executed.
  • Parameter globals(Optional):
    • Type: Dictionary
    • Description: Global namespace.
  • Parameter locals(Optional):
    • Type: Dictionary
    • Description: Local namespace.

Function Description

  • Return Value: Returns the execution result of the expression.
  • Security Warning: Do not use on untrusted inputeval(), as it may lead to code injection attacks.

Examples

Example 1: Basic Usage

Example

# Calculate a mathematical expression
result = eval("1 + 2 + 3")
print(result)  # Output: 6

# Using variables
x = 10
result = eval("x * 2")
print(result)  # Output: 20

# 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 explanation:

  1. eval()Can execute arithmetic expressions.
  2. Can reference defined variables.
  3. Can call built-in functions.

Example 2: Restricted Environment

Example

# Restrict available functions and variables
x = 10
y = 20

# Create a restricted global dictionary
safe_dict = {"x": x, "y": y, "abs": abs}

result = eval("x + y", safe_dict)
print(result)  # Output: 30

# Disallow 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 demonstrates how to improveeval()security by restricting the globals dictionary.


Python3 内置函数Python3 Built-in Functions


Other Extensions