Explanation of basic knowledge points of python constant folding

  • 2021-09-11 20:52:44
  • OfStack

1. Concepts

Constant collapse means finding and evaluating constant expressions at compile time, instead of evaluating them at runtime, which makes the runtime simpler and faster.

2. Examples

In Python, we can use the disassembly module (Disassembler) to get the CPython bytecode to better understand the process of code execution.

When we use the dis module to disassemble the above constant expression, we get the following bytecode:


>>> import dis
>>> dis.dis("day_sec = 24 * 60 * 60")
    0 LOAD_CONST        0 (86400)
    2 STORE_NAME        0 (day_sec)
    4 LOAD_CONST        1 (None)
    6 RETURN_VALUE

As can be seen from the bytecode, it has only one LOAD_CONST and one calculated value of 86400.

This indicates that the CPython interpreter collapses the constant expression 24 * 60 * 60 and replaces it with a calculated value of 86400 during parsing and building the abstract syntax tree.

Extension of knowledge points:

External details of constant collapse

Initially, we shifted our focus to the external implementation details, focusing on where and how CPython implements constant folding.

All AST optimizations (including constant folding) can be found in the ast_opt. c file. The basic starting function is astfold_expr, which collapses all expressions contained in the Python source code.

This function iterates through AST recursively and tries to collapse each constant expression, as shown in the code snippet above:

astfold_expr Before collapsing an expression, it attempts to collapse its subexpressions (operand objects), and then proxies the collapse operation to a specific expression collapse function.

The action-specific collapse function evaluates the expression, returns the calculated constant, and puts it into AST.

For example, whenever astfold_expr encounters a 2-valued operation, it calls fold_binop to recursively evaluate two child operation objects (expressions).

The fold_binop function returns the calculated constant value, as shown in the code snippet above:

The fold_binop function collapses a 2-valued operation by looking at the breed of subsequent operators and then calling its corresponding handler. For example, if the subsequent operation is an addition, it calls PyNumber_Add on its left and right operands in order to calculate the final value.


Related articles: