Python compile() 関数
compile()は、Python でソースコードをコードオブジェクト(code object)にコンパイルするための組み込み関数です。
コンパイルされたコードオブジェクトはexec() 或 eval()実行できます。compile()主にコードの最適化、動的実行、および一般的なコードの事前コンパイルに使用されます。
単語の意味: compile 意为"编译",将源代码转换为可执行代码。
基本構文とパラメータ
構文形式
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
パラメータの説明
- パラメータ source:
- 型: 文字列または AST オブジェクト
- 説明: コンパイルするソースコード。
- 型: 文字列
- 説明: コードの由来の名前。通常はソースファイル名に設定します。
- 型: 文字列
- 説明: コンパイルモード、
'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
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
コード解析:
- mode='eval' は単一の式に使用します。
- 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}秒)
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()動的なコード生成と実行のシナリオで非常に役立ちます。
その他の拡張