Python compile() 函数

Python3 内置函数 Python3 内置函数


compile() 是 Python 中用于将源代码编译为代码对象(code object)的内置函数。

编译后的代码对象可以被 exec()eval() 执行。compile() 主要用于代码优化、动态执行,以及预编译常见代码。

单词释义compile 意为"编译",将源代码转换为可执行代码。


基本语法与参数

语法格式

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

参数说明

  • 参数 source
    • 类型: 字符串或 AST 对象
    • 描述: 要编译的源代码。
  • 参数 filename
    • 类型: 字符串
    • 描述: 代码来源的名称,通常设为源文件名。
  • 参数 mode
    • 类型: 字符串
    • 描述>: 编译模式,'exec'(语句块)、'eval'(表达式)、'single'(单语句)。

函数说明

  • 返回值: 返回一个代码对象。

实例

示例 1:基础用法

实例

# 编译表达式
code = compile("1 + 2", "<string>", "eval")
result = eval(code)
print(result)  # 输出: 3

# 编译语句块
code = compile("print('Hello')", "<string>", "exec")
exec(code)  # 输出: Hello

# 编译多行代码
code = compile("""
x = 10
y = 20
result = x + y
"""
, "<string>", "exec")
exec(code)
print(result)  # 输出: 30

运行结果:

3
Hello
30

代码解析:

  1. mode='eval' 用于单个表达式。
  2. mode='exec' 用于语句块。

示例 2:动态执行代码

实例

# 用户输入的代码
user_code = "for i in range(5): print(i, end=' ')"
code = compile(user_code, "<user>", "exec")
exec(code)  # 输出: 0 1 2 3 4

# 使用 compile 预编译提高性能
import time
code_str = "sum(range(1000))"
compiled = compile(code_str, "<string>", "eval")

start = time.time()
for _ in range(10000):
    eval(compiled)
print(f"编译后: {time.time() - start:.4f}秒")

运行结果:

compile() 可以预编译代码提高执行效率。

compile() 在动态代码生成和执行场景中非常有用。


Python3 内置函数 Python3 内置函数