Python compile () Function

Python Methods and Functions

Syntax :

 compile (source, filename, mode, flags = 0, dont_inherit = False, optimize = -1) 

Parameters:

Source - It can be a normal string, a byte string, or an AST object

Filename -This is the file from which the code was read. If it wasn't read from a file, you can give a name yourself.

Mode - Mode can be exec, eval or single.
a . eval - If the sorce is a single expression.
b. exec - It can take a block of a code that has Python statements, class and functions and so on.
c. single - It is used if consists of a single interactive statement

Flags (optional) and dont_inherit (optional) - Default value = 0. It takes care that which future statements affect the compilation of the source.
Optimize (optional) - It tells optimization level of compiler. Default value -1.

# Python code to demonstrate how compile () works.

 
# Create a sample source code to multiply two variables
# x and y.

srcCode = ' x = 10 y = 20 mul = x * y print ("mul =", mul) '

  
# Convert the above source code to executable

execCode = compile (srcCode, 'mulstring' , ' exec' )

  
# Run executable code.

exec (execCode)

Exit:

 mul = 200 

# Another Python code that demonstrates how compile () works.

x = 50

 
# eval note used for one statement

a = compile ( ' x' , 'test' , 'single' ) < / p>

exec (a)

Exit :

 50 

Applications :

  1. If the Python code is in string form or is an AST object and you want to change it to a code object, then you can use the compile () method.
  2. The code object returned by the compile () method, can later be called using methods such as exec () and eval (), which will execute dynamically generated Python code.




Get Solution for free from DataCamp guru