In the previous article, we have discussed Python Program for bytes() Function
compile() Function in Python:
The compile() function returns the specified source as a ready-to-execute code object.
Syntax:
compile(source, filename, mode, flag, dont_inherit, optimize)
Parameters:
source: This is Required. A String, a Bytes object, or an AST object can be used as the source to compile.
filename: Required. The name of the file from which the source was obtained. If the source is not a file, you can type whatever you want.
mode: This is Required. Legal principles:
- If the source is a single expression, use eval.
- If the source is a set of statements, use exec.
- If the source is a single interactive statement, use single
flag: This is Optional. The process of compiling the source code. 0 is the default.
dont_inherit: This is Optional. The process of compiling the source code. False by default
optimize: This is Optional. Defines the compiler’s optimization level. -1 is the default.
Return value:
Python code object is returned by the compile() function.
Examples:
Example1:
Input:
Given code in string = 'p = 4\nq=7\nmult=p*q\nprint("The multiplication result =",mult)'
Output:
The multiplication result = 28
Example2:
Input:
Given code in string = 'p = 25\nq=5\ndivisn=p/q\nprint("The division result =",divisn)'
Output:
The division result = 5.0
Program for compile() Function in Python
Method #1: Using Built-in Functions (Static Input)
Approach:
- Give the Python code as a string that multiplies the given two numbers and store it in a variable.
- Compile the given code using the compile() function with the parameters as the above string code, codename, and mode of compilation.
- Print the above result which is the code after compilation.
- The Exit of the Program.
Below is the implementation:
# Give the Python code as a string that multiplies the given two numbers # and store it in a variable. codeIn_gvnstring = 'p = 4\nq=7\nmult=p*q\nprint("The multiplication result =",mult)' # Compile the given code using the compile() function with the parameters # as the above string code, codename, and mode of compilation. code_obejct = compile(codeIn_gvnstring, 'multstring', 'exec') # Print the above result which is the code after compilation. exec(code_obejct)
Output:
The multiplication result = 28
Explanation:
In this case, the source is a regular string. multstring is the filename. Furthermore, the exec mode later allows the use of the exec() method.
The compile() method transforms a string into a Python code object. The exec() method is then used to execute the code object.
Find a Comprehensive Collection of Python Built in Functions that you need to be aware of and use them as a part of your program.