compile() Function in Python

Python compile() Function

The compile() function in Python is used to compile a source code string into a code object or AST (Abstract Syntax Tree) object that can be executed later. It takes three arguments: source, filename, and mode.

Here's the syntax of compile() function:

compile(source, filename, mode)
  • source: This parameter specifies the source code string that you want to compile. It can be a string containing a single statement or multiple statements.
  • filename: This parameter specifies the filename associated with the source code. It is optional and can be set to <string> if the source does not originate from a file.
  • mode: This parameter specifies the compilation mode. It can take three possible values:
    • 'exec': This is the default mode and is used when you want to compile a module-level code. It returns a code object.
    • 'eval': This mode is used to compile a single expression and returns the compiled code as an expression object.
    • 'single': This mode is used to compile a single interactive statement and returns the compiled code as a code object.

The compile() function returns the compiled code object or expression object, depending on the mode specified.

Example 1: Compiling a module-level code

source_code = """
def greet(name):
    print("Hello, " + name)

greet("Alice")
"""
compiled_code = compile(source_code, filename='<string>', mode='exec')
exec(compiled_code)

Example 2: Compiling a single expression

expression = "2 + 3 * 4"
compiled_expression = compile(expression, filename='<string>', mode='eval')
result = eval(compiled_expression)
print(result)  # Output: 14

Example 3: Compiling a single interactive statement

statement = "x = 5"
compiled_statement = compile(statement, filename='<string>', mode='single')
exec(compiled_statement)
print(x)  # Output: 5

Note that the compiled code objects can be executed using the exec() function, while compiled expression objects can be evaluated using the eval() function.