In this tutorial, we will discuss about the compile() function in python programming language with the help of examples.
Python compile() function
The built-in python function is used to convert a source code into a ready to execute object code or it can be executed later with the help of and function. The Python source code can be in the normal string form or byte string or an AST object.
Syntax
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
Parameters of compile() function in python
The compile() function in python takes following arguments or parameters;
• - The source code can be in the normal string form or byte string or an AST object.
• - The name of the file from which the code was read. You can give a name by yourself if the code was not read from a file.
• - It can be either exec, eval or single;
a. - It is used when a code consists of python statement, function, class, etc.
b. - It accepts a single expression only.
c. - It is used when source code consists of single interactive statement.
• and ( both optional)- It is used to control which future statement will affect the source compilation.
• (optional)- It is used to tell the optimization level of the compiler. And -1 is the default value.
Return value of Python compile() function
The python function is used to convert a source code into a ready to execute object code.
Example 1: Using exec() method and the compile method converts the string of Python code object
# Python code to demonstrate working of compile() Function# Creating sample srcCode to multiply two variables
src = 'a = 10\nb = 20\nmulti = a * b\nprint("total =", multi)'
# Converting source code to an executable
execC = compile(src, 'mulstring', 'exec')
# Running the executable code
exec(execC)
Output
total = 200
Example 2: Another example of the working of Python compile() function
# Python code to demonstrate working of compile() functiona = 69
# Note: eval is used for single statement
b = compile('a', 'test', 'single')
print(type(a))
exec(b)
Output
<class 'int'>
69
Example 3: Python compile() function from file
test.py: In the above example, with some string display, we have taken test.py file and after reading the content of file, to code the object we have to compile it and then execute it.
Str1 = "Python is an object-oriented programming language"
print(Str1)
Code: Above, the content of the file is read as a string and to a code of object, it is compiled.
# reading code from a filef = open('test.py', 'r')
temp = f.read()
f.close()
code = compile(temp, 'test.py', 'exec')
exec(code)
Output
Python is an object-oriented programming language
Example 4: Python compile() function with eval()
# Python code to demonstrate working of compile() function with evala = 14
# Note eval is used for statement
x = compile('a == 14', '', 'eval')
print(eval(x))
Output
True