Tutorial Study Image

Python compile()

Using the compile() function we can convert a source to a runnable code object.


compile (source, file_name, mode, flags=0, d optimize=-1)#where source can be String,a byte string,or abstract syntax tree

complile() Parameters:

The compile function takes a source as the main input. The other parameters are the source code’s filename, mode to indicate the type of the source, flags, and dont_inherit for indications to the compiler and optimize to specify the level of optimization

Parameter Description Required / Optional
source String, a byte string, or abstract syntax tree(AST) Required
file_name File which is having the source, if source not from a file any name can be given Required
mode 3 possible values -
eval: If the source is a single expression
single: If the source is a single interactive statement
exec: If the source is a block of statement
Required
flags Default zero indicates which future statement affects compilation Optional
dont_inherit Default False, indicates which future statement affects compilation Optional
optimize Optimization level of compiler, default -1 Optional

compile() Return Value

Depending on the parameters passed the source will be converted to a python code object.

Input Return Value
Python Source Python Code object

Examples of compile() method in Python

Example 1: A block of code as source


pythonSource = 'n1 = 10\n n2=20\nsum=n1 + n2 \n print("sum =",sum)'  pyth pythonSource,'randomName','exec') 
exec(pythonCodeObj)
 

Output:

sum = 30

Example 2: A single statement as source


pythonSource = 'print("Hi , I am a single statement)'  pyth pythonSource,'randomName','eval') 
exec(pythonCodeObj)
 

Output:

Hi I am a single statement