Python 2.1 and 2.2 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
In a normal compile a SET_LINENO instruction (opcode 127) comes before
each statement. Its argument is the line number. The -O option leaves
these instructions out, so a .pyo file has none. The compiler’s own
comment says that in -O mode the bytecode offsets are mapped to source
lines through the table instead. 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.
To find the line of an instruction, start with address 0 and line
co_firstlineno. For each pair, add the first byte to the address. If the
address has now gone past the instruction, 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, and the two releases split
it differently. compile.c in 2.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. In 2.2 it writes pairs of 255 and 0 until the address step
fits, then pairs of the remaining address step and 255 until the line step fits, and
then one last pair, so the same step is FF 00 2D 03. A step of 6 bytes and
300 lines is 06 FF 00 2D in both. A reader that adds the pairs up gets the
same answer either way.
Worked example
This example is constructed by hand from compile.c in 2.1 and 2.2, with
no Python this old running it. It is a function on lines 5 to 7:
def f(a):
b = a
return b
| Offset | Bytes | Instruction |
|---|---|---|
| 0 | 7F 05 00 | SET_LINENO 5, the def line |
| 3 | 7F 06 00 | SET_LINENO 6 |
| 6 | 7C 00 00 | LOAD_FAST 0 (a) |
| 9 | 7D 01 00 | STORE_FAST 1 (b) |
| 12 | 7F 07 00 | SET_LINENO 7 |
| 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 5. 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 5, 3 to 11 are line 6, and from 12 on line 7.
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 6 starts at offset 0 and line 7 at offset 6.