How does this internal Python optimization work for mathematical expressions?

Viewed 89

This is an optimization question. I have an expression inside a function like the following:

>>> def x():
...     num = 2 * 4 * 100 * 20
...
>>> x.__code__.co_consts
(None, 2, 4, 100, 20, 8, 800, 16000)

The result of the expression 2 * 4 * 100 * 20 is 16000, so if we disassemble the x:

>>> dis.dis(x)
  2           0 LOAD_CONST               7 (16000)
              3 STORE_FAST               0 (x)
              6 LOAD_CONST               0 (None)
              9 RETURN_VALUE       

The 16000 is pretty much what's need. co_consts stores 8 and 800 which are technically not needed anymore we have the total or are they?

Comparing the above expression with another one:

>>> def x():
...     num = 3 + 4 + 9  * 4
... 
>>> x.__code__.co_consts
(None, 3, 4, 9, 7, 36)

looks like the bytecode compiler takes binary operands and stores their computation values:

9 * 4   36 
3 + 4   7 

disassembling the function:

>>> dis.dis(x)
  2           0 LOAD_CONST               4 (7)
              3 LOAD_CONST               5 (36)
              6 BINARY_ADD          
              7 STORE_FAST               0 (num)
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE   

Interestingly, if you take this expression: 2 + 5 * 8 - 5 + 23 * 4, co_consts will be (None, 2, 5, 8, 23, 4, 40, 92) only the multiplications were computed: 5 * 8 and 23 * 4 the addition and subtraction were ignored.

How does this optimization really work? I tested this only on 2.7.

1 Answers
Related