codehaus


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

constant folding - why not more


On Wed, Nov 11, 2020 at 4:01 AM David Kolovratn?k <david at kolovratnik.net> wrote:
> On the contrary, comparison remains for runtime:
> >>> dis.dis(compile('1 < 2', filename='<string>', mode='eval',
> >>> optimize=2))
>   1           0 LOAD_CONST               0 (1)
>               2 LOAD_CONST               1 (2)
>               4 COMPARE_OP               0 (<)
>               6 RETURN_VALUE
> In function fold_unaryop (though comparison is a binary operation) in
> Python/ast_opt.c is remark: /* Fold not into comparison */
>
> Is there a reason why comparison (== != < > <= >=) is not folded? I would
> expect it handled in fold_binop.

I think that comment is unrelated. It's more about this:

>>> dis.dis(lambda x, y: x is y)
  1           0 LOAD_FAST                0 (x)
              2 LOAD_FAST                1 (y)
              4 IS_OP                    0
              6 RETURN_VALUE
>>> dis.dis(lambda x, y: not (x is y))
  1           0 LOAD_FAST                0 (x)
              2 LOAD_FAST                1 (y)
              4 IS_OP                    1
              6 RETURN_VALUE
>>> dis.dis(lambda x, y: x is not y)
  1           0 LOAD_FAST                0 (x)
              2 LOAD_FAST                1 (y)
              4 IS_OP                    1
              6 RETURN_VALUE

The leading "not" gets folded into the operator, since there's
absolutely no way for "x is not y" and "not (x is y)" to return
different results. Same is true for "not (x in y)".

ChrisA