Surprised by the lack of constant folding

duncan smith duncan at invalid.invalid
Fri Mar 24 16:00:08 EDT 2017


On 24/03/17 19:35, Tim Chase wrote:
> Playing around, I came across the following
> 
> $ python3
> Python 3.4.2 (default, Oct  8 2014, 10:45:20) 
> [GCC 4.9.1] on linux
> Type "help", "copyright", "credits" or "license" for more information.
>>>> from dis import dis
>>>> def f(x):
> ...     return x * 1024 * 1024
> ... 
>>>> dis(f)
>   2           0 LOAD_FAST                0 (x)
>               3 LOAD_CONST               1 (1024)
>               6 BINARY_MULTIPLY
>               7 LOAD_CONST               1 (1024)
>              10 BINARY_MULTIPLY
>              11 RETURN_VALUE
> 
> Is there any reason that Python doesn't do the constant folding of
> 1024 * 1024?  Especially as it does constant folding if the order is
> reversed:
> 
>>>> def f(x):
> ...     return 1024 * 1024 * x
> ... 
>>>> dis(f)
>   2           0 LOAD_CONST               2 (1048576)
>               3 LOAD_FAST                0 (x)
>               6 BINARY_MULTIPLY
>               7 RETURN_VALUE
> 
> 
> I'm cool with defining things as a constant and using those instead
> or front-loading my constants in my expressions, but the disparity
> struck me as a little odd.  Any insights on the reasons/motivations
> for one and not the other?
> 
> -tkc
> 
> 
> 

Left to right evaluation? Depending on the type of x, x * 1024 * 1024
might not return the same result as x * (1024 * 1024). That's my guess.

Duncan


More information about the Python-list mailing list