Python compile() function
The Python compile() function is used to compile source code into a Python code object. Here, the Python code object represents a piece of bytecode that is executable and immutable.
There are two methods named exec() and eval() are used along with the compile() function to execute the compiled code.
The compile() function is one of the built-in functions and does not require any module to import.
Syntax
The syntax of the Python compile() function is as follows −
compile(source, fileName, mode, flag, dont_inherit, optimize)
Parameters
The Python compile() function accepts the following parameters −
source − This parameter represents a string or an AST object.
fileName − It specifies name of the file from which the source will be loaded. If source is not being loaded from a file, specify any name of your choice.
mode − It indicates the kind of code to be compiled. It can be "exec" if source consists of a sequence of statements. If it consists of a single expression, the mode can be "eval" or "single" if source consists of a single interactive statement.
flag − It specifies which future statements affect the compilation of the source. Its default value is 0.
dont_inherit − The default value of this parameter is False. It specifies how to compile the source.
optimize − It represents the optimization level for the compiler.
Return Value
The Python compile() function returns a Python code object.
compile() function Examples
Practice the following examples to understand the use of compile() function in Python:
Example: Use of compile() Function
To execute a single expression, we use eval mode. The following example shows the use of Python compile() function in compiling a single expression in eval mode.
operation = "5 * 5"
compiledExp = compile(operation, '<string>', 'eval')
output = eval(compiledExp)
print("The result after compilation:", output)
When we run above program, it produces following result −
The result after compilation: 25
Example: Execute Two Expressions Using compile()
If the source is sequence of statements, we use the exec mode for execution. In the code below, we have a expression with two statements and we are using the compile() function to compile those statements.
exprsn = "kOne = 'vOne'"
compiledExp = compile(exprsn, '<string>', 'exec')
exec(compiledExp)
print("The value of key after compilation:", kOne)
Following is an output of the above code −
The value of key after compilation: vOne
Example: Execute Multiple Expressions Using compile()
The code below shows how to compile multiple statements using compile() function. Since the source contains multiple expressions, we need to use the exec mode.
exprsn = """
def msg(name):
print('Tutorials' + name)
msg('Point')
"""
compiledExp = compile(exprsn, '<string>', 'exec')
exec(compiledExp)
Output of the above code is as follows −
TutorialsPoint