Python Compilation/Interpretation Process

后端 未结 2 493
执念已碎
执念已碎 2020-11-28 19:36

I\'m trying to understand the python compiler/interpreter process more clearly. Unfortunately, I have not taken a class in interpreters nor have I read much about them.

2条回答
  •  一整个雨季
    2020-11-28 20:00

    To complete the great Marcelo Cantos's answer, here is just a small column-by-column summary to explain the output of disassembled bytecode.

    For example, given this function:

    def f(num):
        if num == 42:
            return True
        return False
    

    This may be disassembled into (Python 3.6):

    (1)|(2)|(3)|(4)|          (5)         |(6)|  (7)
    ---|---|---|---|----------------------|---|-------
      2|   |   |  0|LOAD_FAST             |  0|(num)
       |-->|   |  2|LOAD_CONST            |  1|(42)
       |   |   |  4|COMPARE_OP            |  2|(==)
       |   |   |  6|POP_JUMP_IF_FALSE     | 12|
       |   |   |   |                      |   |
      3|   |   |  8|LOAD_CONST            |  2|(True)
       |   |   | 10|RETURN_VALUE          |   |
       |   |   |   |                      |   |
      4|   |>> | 12|LOAD_CONST            |  3|(False)
       |   |   | 14|RETURN_VALUE          |   |
    

    Each column has a specific purpose:

    1. The corresponding line number in the source code
    2. Optionally indicates the current instruction executed (when the bytecode comes from a frame object for example)
    3. A label which denotes a possible JUMP from an earlier instruction to this one
    4. The address in the bytecode which corresponds to the byte index (those are multiples of 2 because Python 3.6 use 2 bytes for each instruction, while it could vary in previous versions)
    5. The instruction name (also called opname), each one is briefly explained in the dis module and their implementation can be found in ceval.c (the core loop of CPython)
    6. The argument (if any) of the instruction which is used internally by Python to fetch some constants or variables, manage the stack, jump to a specific instruction, etc.
    7. The human-friendly interpretation of the instruction argument

提交回复
热议问题