Surprised by the lack of constant folding

Ian Kelly ian.g.kelly at gmail.com
Fri Mar 24 15:49:49 EDT 2017


On Fri, Mar 24, 2017 at 1:35 PM, Tim Chase
<python.list at tim.thechases.com> 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?

Because that expression is equivalent to (x * 1024) * 1024, not x *
(1024 * 1024).

If x is a built-in type like int or list then that may be equivalent
to x * 1048576, but the compiler can't know that x is necessarily one
of those things.


More information about the Python-list mailing list