Python compile() Function
The compile() function in Python is used to compile source code into a code object that can be executed using the exec() or eval() functions.
This is especially useful when you want to execute Python code that is available as a string.
Syntax
compile(source, filename, mode)
Parameters:
source: A string or AST object containing valid Python code.filename: A name string (usually '<string>' if reading from a string).mode: One of'exec','eval', or'single'.
Returns:
- A code object which can be passed to
exec()oreval().
Modes Explained
'exec': For statements (like loops, function definitions).'eval': For expressions (like2 + 2).'single': For a single interactive statement (like in the REPL).
Example 1: Using compile() with 'eval'
code = "3 + 5"
compiled_code = compile(code, "", "eval")
result = eval(compiled_code)
print(result)
8
Example 2: Using compile() with 'exec'
code = """
for i in range(3):
print("Line", i)
"""
compiled = compile(code, "", "exec")
exec(compiled)
Line 0
Line 1
Line 2
Example 3: Using compile() with 'single'
code = "print('Hello')"
compiled = compile(code, "", "single")
exec(compiled)
Hello
Use Cases
- Dynamically executing user-generated Python code.
- Building a code editor, REPL, or interactive shell.
- Converting strings into executable logic.
Common Mistakes
- Using
'eval'for code that includes statements likeiforforwill raise aSyntaxError. - Always validate untrusted code before executing.
Interview Tip
In advanced interviews or coding tools, compile() is used to simulate a mini Python interpreter. It shows your understanding of dynamic code execution.
Summary
compile()turns code strings into code objects.- Use
eval()orexec()to run the compiled code. - Modes:
'exec'(statements),'eval'(expressions),'single'(REPL).
Practice Problem
Write a program that reads an arithmetic expression from the user, compiles it, and evaluates the result.
user_input = input("Enter an arithmetic expression: ")
code_obj = compile(user_input, "", "eval")
result = eval(code_obj)
print("Result:", result)
Comments
Loading comments...