Skip to content

Latest commit

 

History

History
38 lines (32 loc) · 1.34 KB

20240131112257.md

File metadata and controls

38 lines (32 loc) · 1.34 KB

dis module

The dis module supports the analysis of CPython bytecode by disassembling it - see example below.

Here we wrote a little function called hello passing it to dis.dis() which explains its bytecode.

Meaning of the columns: • source code line number • numerical offset (in bytes) from the start of the code object’s bytecode string to the current instruction • name of the bytecode operation (opcode) • argument for the opcode, if applicable • human-readable interpretation of what that argument represents • additional information might be provided under this column

>>> def hello(name=None):
...     name = 'Stranger' if name is None else name
...     return f"Hello {name}"
...
>>> import dis
>>> dis.dis(hello)
  2           0 LOAD_FAST                0 (name)
              2 LOAD_CONST               0 (None)
              4 IS_OP                    0
              6 POP_JUMP_IF_FALSE       12
              8 LOAD_CONST               1 ('Stranger')
             10 JUMP_FORWARD             2 (to 14)
        >>   12 LOAD_FAST                0 (name)
        >>   14 STORE_FAST               0 (name)

  3          16 LOAD_CONST               2 ('Hello ')
             18 LOAD_FAST                0 (name)
             20 FORMAT_VALUE             0
             22 BUILD_STRING             2
             24 RETURN_VALUE

#dis