In Python, compile() is a built-in function that compiles strings or AST objects into bytecode or code objects. The compiled bytecode or code objects can be executed across multiple Python interpreters, avoiding the need to recompile code each time it's executed.
compile() Function Syntax
The syntax for the compile() function is:
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
Parameter descriptions:
source: Required, represents the source code to compile. Can be a string, AST object, or readable object.filename: Required, represents the filename of the source code. If the source code doesn't come from a file, you can use a dummy filename.mode: Required, represents the compilation mode. Can be one of three values:- "exec": Used to compile code blocks containing Python statements, such as modules, functions, or classes.
- "eval": Used to compile code blocks containing a single Python expression.
- "single": Used to compile code blocks containing a single Python statement.
flags: Optional, represents compiler flags. Default value is 0, multiple flags can be combined using bitwise OR operations.This parameter is typically not used; refer to the
astmodule documentation for detailed usage.dont_inherit: Optional, indicates whether to inherit flags from the parent scope. Default value isFalse.optimize: Optional, represents optimization level. Default value is -1, indicating default optimization level. Can be one of three values:- 0: No optimization.
- 1: Simple optimization.
- 2: Aggressive optimization.
Return Value
Returns a code object that can be executed by exec() and eval().
Example Code
Using exec mode:
source = "print('hello, world!')"
code = compile(source, "test.py", "exec")
exec(code) # Outputs "hello, world!"
Using eval mode:
a = 5
source = "a * 2 + a"
compiled_expr = compile(source, 'test.py', 'eval')
result = eval(compiled_expr)
print(result) # Output: 15
Using flags parameter to generate only AST without compiling to bytecode:
import ast
code = """
def foo(a, b):
return a * b + 5
result = foo(3, 4)
"""
# Generate only AST, don't compile to bytecode
ast_object = compile(code, 'test.py', 'exec', flags=ast.PyCF_ONLY_AST)
print("Type:", type(ast_object))
print("AST Content:")
print(ast.dump(ast_object, indent=2))
Program Output
Type: <class 'ast.Module'>
AST Content:
Module(
body=[
FunctionDef(
name='foo',
args=arguments(
posonlyargs=[],
args=[
arg(arg='a'),
arg(arg='b')],
kwonlyargs=[],
kw_defaults=[],
defaults=[]),
body=[
Return(
value=BinOp(
left=BinOp(
left=Name(id='a', ctx=Load()),
op=Mult(),
right=Name(id='b', ctx=Load())),
op=Add(),
right=Constant(value=5)))],
decorator_list=[]),
Assign(
targets=[
Name(id='result', ctx=Store())],
value=Call(
func=Name(id='foo', ctx=Load()),
args=[
Constant(value=3),
Constant(value=4)],
keywords=[]))],
type_ignores=[])