These releases record source lines in two ways at once: SET_LINENO
instructions in the bytecode, and the table co_lnotab in the code object.
The explorer works out line numbers from the table.
SET_LINENO
A normal compile puts a SET_LINENO instruction (opcode 127) before each
statement. Its argument is the line number, and at run time it stores that number in
the frame. It costs an instruction for every statement, so the -O option
leaves them out, and a .pyo file has none. The table is written either
way.
The co_lnotab table
co_lnotab is a string of byte pairs. The first byte of a pair is how far
the address moves on, in bytes of co_code. The second is how far the line
number moves on. Both are unsigned, so neither can go down.
To read it, start with address 0 and line co_firstlineno. For each pair,
add the first byte to the address, and if the address is now past the instruction you
are looking for, stop: the line so far is its line. Otherwise add the second byte to
the line and go on.
A step too big for one byte is spread over several pairs. compile.c in
1.5.2 and 2.0.1 cuts the address step and the line step at 255 together, so a step of
300 bytes and 3 lines is written as FF 03 2D 00: 255 bytes and 3 lines,
then 45 bytes and no lines. A reader that adds the pairs up does not need to know
this. It only matters if you try to read a single pair on its own.
Worked example
This example is constructed by hand from compile.c in 1.5.2, with no
Python this old running it. It is this function:
def f(a):
b = a
return b
| Offset | Bytes | Instruction |
|---|---|---|
| 0 | 7F 01 00 | SET_LINENO 1, the def line |
| 3 | 7F 02 00 | SET_LINENO 2 |
| 6 | 7C 00 00 | LOAD_FAST 0 (a) |
| 9 | 7D 01 00 | STORE_FAST 1 (b) |
| 12 | 7F 03 00 | SET_LINENO 3 |
| 15 | 7C 01 00 | LOAD_FAST 1 (b) |
| 18 | 53 | RETURN_VALUE |
| 19 | 64 00 00 | LOAD_CONST 0 (None), which the compiler adds at the end of every function |
| 22 | 53 | RETURN_VALUE |
A function’s code starts with a SET_LINENO for its def
line, and that first one sets co_firstlineno, here 1. Each later
SET_LINENO adds a pair: how far the code has moved on since the last
one, and how far the line has. That gives 03 01 09 01. A pair is added
even when the line has not changed, as long as the code has moved on. Reading it
back, offsets 0 to 2 are line 1, 3 to 11 are line 2, and from 12 on line 3.
In a .pyo file the SET_LINENO instructions are not
written, but the table is worked out in the same way. The code is
LOAD_FAST 0 at 0, STORE_FAST 1 at 3,
LOAD_FAST 1 at 6 and so on, and the table is 00 01 06 01:
line 2 starts at offset 0 and line 3 at offset 6.