This is the work of the Python peephole optimizer. It evaluates simple operations only with constants during compilation itself and saves the result as a constant in the generated bytecode.
Quote from Python 2.7.9 Source Code ,
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;
Basically, he is looking for instructions like this
LOAD_CONST c1
LOAD_CONST c2
BINARY_OPERATION
and evaluates it and replaces these instructions with result and command LOAD_CONST. Quoting a comment in a functionfold_binops_on_constants ,
,
case BINARY_ADD:
newconst = PyNumber_Add(v, w);
break;