I'm studying Python bytecode, and I find that there is a POP_TOP
instruction after the CALL_FUNCTION
instruction. What does the POP_TOP
do here?
a = 1
b = 2
c = a + b
print(c)
def func(e, f, g):
h = e + f + g
func(a, b, c)
After run python3 -m dis main.py
, I got
1 0 LOAD_CONST 0 (1)
2 STORE_NAME 0 (a)
2 4 LOAD_CONST 1 (2)
6 STORE_NAME 1 (b)
3 8 LOAD_NAME 0 (a)
10 LOAD_NAME 1 (b)
12 BINARY_ADD
14 STORE_NAME 2 (c)
4 16 LOAD_NAME 3 (print)
18 LOAD_NAME 2 (c)
20 CALL_FUNCTION 1
22 POP_TOP
5 24 LOAD_CONST 2 (<code object func at 0x7fb9aebb59c0, file "btins3.py", line 5>)
26 LOAD_CONST 3 ('func')
28 MAKE_FUNCTION 0
30 STORE_NAME 4 (func)
8 32 LOAD_NAME 4 (func)
34 LOAD_NAME 0 (a)
36 LOAD_NAME 1 (b)
38 LOAD_NAME 2 (c)
40 CALL_FUNCTION 3
42 POP_TOP
44 LOAD_CONST 4 (None)
46 RETURN_VALUE
Please see line 22 and line 42 .
There is no such thing as a function which "returns nothing" in Python. Even when a function doesn't explicitly return
a value, the function implicitly returns None
(if you dis.dis(func)
you'll see it in the generated bytecode).
If it didn't do this, the byte code compiler would need to be more complex, because it would need some way to differentiate between functions with and without return values (and since functions are first class objects and can be reassigned, you can't even do this with compile time rules; it would have to be handled on a call-by-call basis at runtime); as is, it can unconditionally treat them as having return values, it's just that some return values (implicit None
) are less useful than others.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.