惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Visual Studio Blog
J
Java Code Geeks
H
Hackread – Cybersecurity News, Data Breaches, AI and More
D
Docker
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 聂微东
MyScale Blog
MyScale Blog
H
Help Net Security
Last Week in AI
Last Week in AI
T
The Blog of Author Tim Ferriss
M
MIT News - Artificial intelligence
大猫的无限游戏
大猫的无限游戏
酷 壳 – CoolShell
酷 壳 – CoolShell
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
P
Proofpoint News Feed
博客园 - 叶小钗
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
F
Fortinet All Blogs
Martin Fowler
Martin Fowler
Microsoft Security Blog
Microsoft Security Blog
T
Tailwind CSS Blog
aimingoo的专栏
aimingoo的专栏

Stonecharioteer on Tech

I Traced My Traffic Through a Home Tailscale Exit Node What Was I Reading Last? In Three Not-So-Easy Pieces Dogfooding Is Hard Code blocks in your books, finally GoForGo v0.9.0 Merrilin - We built an app to read books I use a Macbook now Data Structures & Algorithms - Preparing for Interviews Using a local DNS namespace for local service discovery Direction KOllector - Publishing KOReader Highlights gbt: branches touched in the last 24 hours A Soiree into Symbols in Ruby Some Smalltalk about Ruby Loops Ruby Blocks Returning from Ruby Blocks, Procs and Lambdas My Linux Laptop Finally Works: How Claude Helped Me Fix Years of Annoyances TIL: Watchexec - Modern File Watching for Development Workflows A Less Busy Mind GoForGo - Learn Go through live examples Migrating My Old Blog to Hugo with Claude The Qtile Window Manager: A Python-Powered Tiling Experience Read the RFCs that Built the Internet Py-x-Protobuf - Or How I Learned to Stop Worrying and Love Protocol Buffers Python Reverse a List New Beginnings Leaving ChainSafe Systems Screen Lock for Cinnamon Desktop using Zenity and Terminal Commands Crews Not Teams A System for Getting Better at LeetCode
TIL: Python eval(), exec(), and compile() Functions
2021-03-14 · via Stonecharioteer on Tech

Python Dynamic Code Execution Functions

What’s the difference between eval, exec, and compile? - Stack Overflow

Understanding the three core functions for dynamic code execution in Python:

eval() - Expression Evaluation

Purpose: Evaluates a single Python expression and returns the result

1
2
3
result = eval("2 + 3 * 4")  # Returns 14
x = 5
result = eval("x * 2")      # Returns 10

Characteristics:

  • Single Expression: Only works with expressions, not statements
  • Return Value: Always returns a value
  • Use Cases: Mathematical calculations, simple expressions
  • Limitations: Cannot handle statements like assignments or loops

exec() - Statement Execution

Purpose: Executes Python statements (does not return a value)

1
2
3
4
5
exec("x = 10; y = 20; print(x + y)")  # Prints: 30
exec("""
for i in range(3):
    print(f"Hello {i}")
""")

Characteristics:

  • Multiple Statements: Can execute complex code blocks
  • No Return Value: Returns None
  • Use Cases: Dynamic code execution, configuration scripts
  • Flexibility: Can handle any valid Python code

compile() - Code Object Creation

Purpose: Compiles source code into code objects for repeated execution

1
2
3
4
5
6
# Compile once, execute multiple times
code = compile("x * 2", "<string>", "eval")
x = 5
result1 = eval(code)  # Returns 10
x = 10
result2 = eval(code)  # Returns 20

Modes:

  • ’eval’: For expressions (use with eval())
  • ’exec’: For statements (use with exec())
  • ‘single’: For single interactive statements

Performance Considerations

Compilation Overhead:

  • eval() and exec() compile code every time
  • compile() allows pre-compilation for repeated use
  • Significant performance improvement for repeated execution

Example - Repeated Execution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import timeit

# Without compile() - slower
def slow_version():
    for i in range(1000):
        eval("2 + 3 * 4")

# With compile() - faster
code = compile("2 + 3 * 4", "<string>", "eval")
def fast_version():
    for i in range(1000):
        eval(code)

Security Considerations

Major Risks:

  • Code Injection: User input can execute arbitrary code
  • System Access: Malicious code can access file system, network
  • Data Exposure: Can access and modify global variables

Safer Alternatives:

1
2
3
4
5
6
7
8
# Restricted globals and locals
safe_globals = {"__builtins__": {}}
safe_locals = {"x": 10, "y": 20}
result = eval("x + y", safe_globals, safe_locals)

# Use ast.literal_eval for safe data parsing
import ast
data = ast.literal_eval("{'key': 'value'}")  # Only literals

Best Practices

  1. Avoid When Possible: Use alternative approaches first
  2. Sanitize Input: Never execute untrusted user input
  3. Restrict Scope: Use limited globals and locals dictionaries
  4. Use ast.literal_eval: For parsing data structures safely
  5. Pre-compile: Use compile() for repeated execution

These functions provide powerful dynamic execution capabilities but require careful consideration of security and performance implications.