I just read this SE question about parameter optimisation. I wondered if Python3 bytecode compilation does the same optimisation and this appeared not to be the case:
>>> def f(a): return 2*a
>>> def g(a): r=2*a; return r
>>> import dis
>>> dis.dis(f)
1 0 LOAD_CONST 1 (2)
2 LOAD_FAST 0 (a)
4 BINARY_MULTIPLY
6 RETURN_VALUE
>>> dis.dis(g)
1 0 LOAD_CONST 1 (2)
2 LOAD_FAST 0 (a)
4 BINARY_MULTIPLY
6 STORE_FAST 1 (r)
8 LOAD_FAST 1 (r)
10 RETURN_VALUE
Checking the compilation flags showed that optimization is on:
>>> print(dis.code_info(f))
Name: f
Filename: <stdin>
Argument count: 1
Kw-only arguments: 0
Number of locals: 1
Stack size: 2
Flags: OPTIMIZED, NEWLOCALS, NOFREE
Constants:
0: None
1: 2
Variable names:
0: a
So my question is: why doesn't Python3 optimise out the variable?
Ps: I'm not sure if this questions fits better on SE or on SO. I picked SE because the question that triggered my questions was on SE. If you think this question better fits SO, please let me know...