When does python compile the constant string letters, to combine the strings into a single constant string?

前端 未结 2 1933
执笔经年
执笔经年 2021-01-05 12:41

such as

In [9]: dis.disassemble(compile("s = \'123\' + \'456\'", "", "exec"))
  1           0 LOAD_CONST                 


        
2条回答
  •  天命终不由人
    2021-01-05 13:40

    It happens whenever the combined string is 20 characters or fewer.

    The optimization occurs in the peephole optimizer. See line 219 in the fold_binops_on_constants() function in Python/peephole.c: http://hg.python.org/cpython/file/cd87afe18ff8/Python/peephole.c#l149

提交回复
热议问题