>>> import dis
>>> def f(x):
... return 1+2+3+4+x
...
>>> f(5)
15
>>> dis.dis(f)
2 0 LOAD_CONST 7 (10)
3 LOAD_FAST 0 (x)
6 BINARY_ADD
7 RETURN_VALUE
>>> def g(x):
... return x+1+2+3+4
...
>>> dis.dis(g)
2 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (1)
6 BINARY_ADD
7 LOAD_CONST 2 (2)
10 BINARY_ADD
11 LOAD_CONST 3 (3)
14 BINARY_ADD
15 LOAD_CONST 4 (4)
18 BINARY_ADD
19 RETURN_VALUE
Constant folding in Python: think about why the bytecodes generated for f() and g() are different
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment