The field co_lnotab, the last in a
code object, says which source line
each instruction came from. It is a bytes object made of two-byte pairs: an address step
and a line step.
How to read it
Start with the address at 0 and the line at co_firstlineno. Both steps of
each pair are unsigned bytes. The instructions from the current address up to, but not
including, the new address belong to the current line. Then add both steps.
addr = 0
line = co_firstlineno
for addr_step, line_step in pairs:
addr += addr_step
if addr > target:
return line
line += line_step
return line
The last line reached applies to every instruction after the final pair. Because a step cannot be negative, the table can only move forward through the source.
Large steps
A step over 255 is spread over several pairs. An address step over 255 uses extra
pairs of 255, 0 first, and a line step over 255 uses extra pairs of
0, 255 after the first.
A worked example
This example is constructed by hand from the rule above; it was not compiled by CPython 3.3, 3.4 or 3.5. Take a module of three lines:
a = 1
b = 2
print(a + b)
Every instruction here takes three bytes, apart from the BINARY_ADD,
POP_TOP and RETURN_VALUE at the end, so each assignment takes
six bytes. co_firstlineno is 1 and co_lnotab is
06 01 06 01:
| Pair | Address step | Line step | Result |
|---|---|---|---|
06 01 | +6 | +1 | Offsets 0 to 5 are line 1; now address 6, line 2 |
06 01 | +6 | +1 | Offsets 6 to 11 are line 2; now address 12, line 3 |
Offsets from 12 onwards are line 3.