What is the process of compilation and linking in python?



Compilation: The source code in python is saved as a .py file which is then compiled into a format known as byte code, byte code is then converted to machine code. After the compilation, the code is stored in .pyc files and is regenerated when the source is updated. This process is known as compilation.

Linking: Linking is the final phase where all the functions are linked with their definitions as the linker knows where all these functions are implemented. This process is known as linking.

Example

import dis
def recursive_sum(n):
"""Function to return the sum of recursive numbers"""
if n <= 1:
return n
else:
return n + recursive_sum(n-1)

# change this value for a different result
number = 16
if number < 0:
print("The sum is",recursive_sum(number))
# by using dis module ,the bytecode is loaded into machine code ,and a piece of code that reads each instruction in the bytecode and executes whatever operation is indicated.
dis.dis(recursive_sum)

Output

The sum is 136
4 0 LOAD_FAST 0 (n)
2 LOAD_CONST 1 (1)
4 COMPARE_OP 1 (<=)
6 POP_JUMP_IF_FALSE 12

5 8 LOAD_FAST 0 (n)
10 RETURN_VALUE

7 >> 12 LOAD_FAST 0 (n)
14 LOAD_GLOBAL 0 (recursive_sum)
16 LOAD_FAST 0 (n)
18 LOAD_CONST 1 (1)
20 BINARY_SUBTRACT
22 CALL_FUNCTION 1
24 BINARY_ADD
26 RETURN_VALUE
28 LOAD_CONST 2 (None)
30 RETURN_VALUE
raja
Sri
Published on 27-May-2019 15:54:16
Advertisements