为什么1 + 1不使用BINARY_ADD?

usu*_* me 4 python python-2.7 python-internals

我这样做:

>>> dis.dis(lambda: 1 + 1)
0 LOAD_CONST        2 (2)
3 RETURN_VALUE
Run Code Online (Sandbox Code Playgroud)

我期待BINARY_ADD操作码来执行添加.如何计算总和?

the*_*eye 8

这是Python的窥视孔优化器的工作.它在编译时自身仅使用常量来评估简单操作,并将结果作为常量存储在生成的字节码中.

引用Python 2.7.9源代码,

            /* Fold binary ops on constants.
               LOAD_CONST c1 LOAD_CONST c2 BINOP -->  LOAD_CONST binop(c1,c2) */
        case BINARY_POWER:
        case BINARY_MULTIPLY:
        case BINARY_TRUE_DIVIDE:
        case BINARY_FLOOR_DIVIDE:
        case BINARY_MODULO:
        case BINARY_ADD:
        case BINARY_SUBTRACT:
        case BINARY_SUBSCR:
        case BINARY_LSHIFT:
        case BINARY_RSHIFT:
        case BINARY_AND:
        case BINARY_XOR:
        case BINARY_OR:
            if (lastlc >= 2 &&
                ISBASICBLOCK(blocks, i-6, 7) &&
                fold_binops_on_constants(&codestr[i-6], consts)) {
                i -= 2;
                assert(codestr[i] == LOAD_CONST);
                cumlc = 1;
            }
            break;
Run Code Online (Sandbox Code Playgroud)

基本上,它寻找这样的指令

LOAD_CONST c1
LOAD_CONST c2
BINARY_OPERATION
Run Code Online (Sandbox Code Playgroud)

并评估并用结果和LOAD_CONST指令替换这些指令.引用函数中注释fold_binops_on_constants,

/* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP
   with    LOAD_CONST binop(c1,c2)
   The consts table must still be in list form so that the
   new constant can be appended.
   Called with codestr pointing to the first LOAD_CONST.
   Abandons the transformation if the folding fails (i.e.  1+'a').
   If the new constant is a sequence, only folds when the size
   is below a threshold value.  That keeps pyc files from
   becoming large in the presence of code like:  (None,)*1000.
*/
Run Code Online (Sandbox Code Playgroud)

这个特定代码的实际评估发生在这个块中,

    case BINARY_ADD:
        newconst = PyNumber_Add(v, w);
        break;
Run Code Online (Sandbox Code Playgroud)