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.
source_code = """
def greet(name):
print("Hello, " + name)
greet("Alice")
"""
compiled_code = compile(source_code, filename='<string>', mode='exec')
exec(compiled_code)
expression = "2 + 3 * 4"
compiled_expression = compile(expression, filename='<string>', mode='eval')
result = eval(compiled_expression)
print(result) # Output: 14
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.