Reputation: 141
I am learning about compile() and the dis
module. If I have all my code in the same module, I can see how every line in compiled. I am now trying to understand how code from multiple modules is compiled.
For this, I have the following two files.
#test.py
import sys
from temp import doubler
def tripler(n: int) -> int:
f = 3 * n
return f
if __name__ == '__main__':
n = int(sys.argv[1]) if len(sys.argv) > 1 else 4
t = tripler(n)
s = doubler(t)
print(s)
#temp.py
def doubler(x):
y = 2 * x
return y
I then run compile() for the text from test.py and the output of dis.dis() is as follows
0 0 RESUME 0
1 2 LOAD_CONST 0 (0)
4 LOAD_CONST 1 (None)
6 IMPORT_NAME 0 (sys)
8 STORE_NAME 0 (sys)
2 10 LOAD_CONST 0 (0)
12 LOAD_CONST 2 (('doubler',))
14 IMPORT_NAME 1 (temp)
16 IMPORT_FROM 2 (doubler)
18 STORE_NAME 2 (doubler)
20 POP_TOP
4 22 LOAD_CONST 3 ('n')
24 LOAD_NAME 3 (int)
26 LOAD_CONST 4 ('return')
28 LOAD_NAME 3 (int)
30 BUILD_TUPLE 4
32 LOAD_CONST 5 (<code object tripler at 0x00000255AB98F910, file "test.py", line 4>)
34 MAKE_FUNCTION 4 (annotations)
36 STORE_NAME 4 (tripler)
9 38 LOAD_NAME 5 (__name__)
40 LOAD_CONST 6 ('__main__')
42 COMPARE_OP 40 (==)
46 POP_JUMP_IF_FALSE 69 (to 186)
10 48 PUSH_NULL
50 LOAD_NAME 6 (len)
52 LOAD_NAME 0 (sys)
54 LOAD_ATTR 14 (argv)
74 CALL 1
82 LOAD_CONST 7 (1)
84 COMPARE_OP 68 (>)
88 POP_JUMP_IF_FALSE 21 (to 132)
90 PUSH_NULL
92 LOAD_NAME 3 (int)
94 LOAD_NAME 0 (sys)
96 LOAD_ATTR 14 (argv)
116 LOAD_CONST 7 (1)
118 BINARY_SUBSCR
122 CALL 1
130 JUMP_FORWARD 1 (to 134)
>> 132 LOAD_CONST 8 (10)
>> 134 STORE_NAME 8 (n)
11 136 PUSH_NULL
138 LOAD_NAME 4 (tripler)
140 LOAD_NAME 8 (n)
142 CALL 1
150 STORE_NAME 9 (t)
12 152 PUSH_NULL
154 LOAD_NAME 2 (doubler)
156 LOAD_NAME 9 (t)
158 CALL 1
166 STORE_NAME 10 (s)
13 168 PUSH_NULL
170 LOAD_NAME 11 (print)
172 LOAD_NAME 10 (s)
174 CALL 1
182 POP_TOP
184 RETURN_CONST 1 (None)
9 >> 186 RETURN_CONST 1 (None)
Disassembly of <code object tripler at 0x00000255AB98F910, file "test.py", line 4>:
4 0 RESUME 0
5 2 LOAD_CONST 1 (3)
4 LOAD_FAST 0 (n)
6 BINARY_OP 5 (*)
10 STORE_FAST 1 (f)
7 12 LOAD_FAST 1 (f)
14 RETURN_VALUE
I can see that the symbol doubler is imported from temp. I cannot see the codeobject for it though. I also don't understand at which stage it is even compiled. The code object executes fine. Can someone explain what happens with the module temp?
Upvotes: 0
Views: 35