How to Build a Line-Coverage Tool With sys.monitoring in Python 3.12+, Make It Nearly Free With DISABLE, and Check It Against coverage.py and sys.settrace
Build a small line-coverage tool on Python’s sys.monitoring, measure four versions against sys.settrace and coverage.py, and test the tool with 19 tests and 13 planted bugs.
A green test run tells you that the tests you wrote passed. It does not tell you which parts of your program those tests ever ran. A coverage tool answers that second question: it watches the program while it runs, remembers every line that executed, and afterwards lists the lines that never did. Those are the places where a bug can hide without a single test noticing.
Table Of Content
- What you will build
- The words you need first
- Prerequisites
- Set up the folder and the program to measure
- Step 1: Watch the interpreter report lines
- Step 2: Claim a tool ID and expect a collision
- Step 3: Version 1, record every line
- Step 4: Version 2, keep only your own files
- Step 5: Version 3, say it once and return DISABLE
- Step 6: Version 4, only ask about your own code
- The catch: the function that called start()
- The four versions side by side
- Step 7: The finished tool, a report and a command line
- The finished tool, piece by piece
- Claiming an ID politely
- Watching already-running code
- Stopping cleanly
- The denominator
- Contexts
- Close the hole from step 6
- Run it on the test suite
- Check the answers against two independent tools
- Step 8: Find out which test ran which line
- Step 9: Measure the cost
- Results on Python 3.13.14
- The same benchmark on Python 3.15.2
- Step 10: Traps worth knowing before you ship a tool
- Trap 1: free_tool_id used to leave things behind
- Trap 2: errors in your callback surface in the monitored code
- Trap 3: threads are seen, other processes are not
- Trap 4: a disabled line has no count
- Step 11: Test the tool and plant bugs to see who notices
- Common mistakes, in one place
- Confirm that everything works end to end
- Where to go next
- Sources and further reading
The hard part is watching without slowing the program to a crawl. For many years the standard Python hook for this was sys.settrace, which calls a Python function for every line that runs. Python 3.12 added a newer interface, sys.monitoring, in which a tool chooses the events it wants and, more importantly, can answer “I have seen this spot, do not tell me about it again”. For a coverage tool that answer is exactly right, because knowing that a line ran once is enough.
In this tutorial you will build a small line-coverage tool called linecov in four versions and watch the cost of each one fall. You will compare its answers with sys.settrace and with coverage.py, run it over a pytest session, find out which test ran which line, and then test the tool itself by planting 13 bugs in it to see whether its tests notice. Everything runs on your own machine with Python and two pip packages. No account, server or paid service is involved.
What you will build
- four small versions of a
LineCoverageclass (linecov_v1.pytolinecov_v4.py), each fixing one problem of the one before; - a finished
linecov.pywith a coverage report, a command-line runner (covrun.py) and per-test contexts; - a benchmark that runs every version, a pure-Python
sys.settracetracer and coverage.py in fresh processes on Python 3.13.14 and 3.15.2; - a cross-check that proves the tool finds the same lines as
sys.settraceand coverage.py, and a 19-test suite plus a 13-bug mutation check for the tool itself.
The words you need first
The vocabulary is small. Read it once and the rest of the post will make sense.
- Event. Something the interpreter can tell a tool about, for example “a line is about to run” (
LINE) or “a function has just started” (PY_START). - Callback. A function of yours that Python calls when an event happens. For a
LINEevent it receives the code object and the line number. - Code object. The compiled form of a function, a module body or a class body. It knows its file name (
co_filename) and which bytecode belongs to which line (co_lines()). - Tool ID. A number from 0 to 5 that a tool claims before it uses monitoring, so that a debugger, a coverage tool and a profiler can work at the same time without trampling each other.
- Executable line. A line that produces bytecode. Blank lines, comments and a bare
else:do not. Coverage is the share of executable lines that ran. DISABLE. A special value a callback can return to say “stop reporting this spot”. It is the reasonsys.monitoringcan be fast.
Prerequisites
- Python 3.12 or newer. Everything here was run on Windows 11 with Python 3.13.14, and every step except the mutation check was repeated on 3.15.2. On macOS and Linux only the way you activate the virtual environment differs.
- pytest 9.2.0, and coverage 7.17.5 for the comparison steps. Both install with pip below.
- You can read a Python class and a function. You do not need to know anything about bytecode.
- About an hour. The benchmarks in step 9 take a few minutes to run.
Set up the folder and the program to measure
Create a folder with its own virtual environment, so nothing you install touches the rest of your machine. The block below uses the Windows cmd.exe form of the activation line. In PowerShell use .venv\Scripts\Activate.ps1, and on macOS and Linux use source .venv/bin/activate.
mkdir covlab
cd covlab
python -m venv .venv
.venv\Scripts\activate
python -m pip install pytest==9.2.0 coverage==7.17.5
mkdir app
mkdir tests
mkdir tooltests
Everything we measure lives in app/, so that your own code is separate from the tests and from the tool. The program is a tiny order calculator. It has branches on purpose: some of its lines are easy to reach and some are not.
# app/shop.py
"""A tiny order calculator: the code we want to measure."""
def parse_quantity(text):
text = text.strip()
if not text.isdigit():
raise ValueError(f"not a number: {text!r}")
quantity = int(text)
if quantity == 0:
raise ValueError("quantity must be at least 1")
return quantity
def unit_price(sku):
prices = {"pen": 150, "ink": 900, "pad": 450}
return prices[sku]
def discount_percent(quantity):
if quantity >= 100:
return 20
if quantity >= 10:
return 10
return 0
def shipping_cents(total_cents, country):
if country == "US":
return 0 if total_cents >= 5000 else 499
if country == "CA":
return 899
return 1999
def order_total(sku, quantity_text, country="US"):
quantity = parse_quantity(quantity_text)
subtotal = unit_price(sku) * quantity
discount = subtotal * discount_percent(quantity) // 100
total = subtotal - discount
return total + shipping_cents(total, country)
Three tests that cover the easy paths come next. A small pytest.ini puts app and the project folder on the import path, so import shop and import linecov work from the tests.
# tests/test_shop.py
import pytest
import shop
def test_small_order_pays_shipping():
assert shop.order_total("pen", "3") == 150 * 3 + 499
def test_ten_inks_get_ten_percent_off():
assert shop.order_total("ink", "10") == 8100
def test_bad_quantity_is_refused():
with pytest.raises(ValueError):
shop.order_total("pen", "many")
# pytest.ini
[pytest]
pythonpath = app .
testpaths = tests
addopts = -p no:cacheprovider
Run them to make sure the starting point is green. The timing will differ on your machine.
python -m pytest -q tests/test_shop.py
... [100%]
3 passed in 0.01s
Step 1: Watch the interpreter report lines
Before building anything, look at what sys.monitoring actually tells you. This script watches a tiny function and prints every LINE event. Note that sys.monitoring is a namespace inside sys, not a module, so you write sys.monitoring and never import sys.monitoring.
# step01_first_events.py
import sys
mon = sys.monitoring
TOOL = mon.COVERAGE_ID
def on_line(code, line_number):
print(f" LINE event: {code.co_name}, line {line_number}")
def greet(name):
text = "hello " + name
if name == "":
text = "hello nobody"
return text
mon.use_tool_id(TOOL, "first-look")
mon.register_callback(TOOL, mon.events.LINE, on_line)
mon.set_events(TOOL, mon.events.LINE)
print("calling greet('ada')")
greet("ada")
mon.set_events(TOOL, mon.events.NO_EVENTS)
mon.register_callback(TOOL, mon.events.LINE, None)
mon.free_tool_id(TOOL)
print("done")
The script does five things in order. It claims tool ID 1 (COVERAGE_ID) with use_tool_id. It registers on_line as the callback for LINE events. It turns that event on with set_events, which is global: from that moment every line that runs anywhere reports. It calls greet("ada"). Finally it turns events off, unregisters the callback and gives the ID back with free_tool_id.
python step01_first_events.py
LINE event: <module>, line 22
calling greet('ada')
LINE event: <module>, line 23
LINE event: greet, line 13
LINE event: greet, line 14
LINE event: greet, line 16
LINE event: <module>, line 24
done
Read this output slowly, because it teaches three facts. First, the docs define a LINE event as “An instruction is about to be executed that has a different line number from the preceding instruction.” The word is about: the event for line 22 appears before calling greet('ada') is printed, because Python reports the line first and runs it second. Second, line 15 of the script, text = "hello nobody", never appears, because name was not empty. A line that never reports is exactly what a coverage tool is looking for. Third, the module itself reports as <module>: top-level code is a code object like any function, so the lines that start and stop the tool are reported too.
If the script stops with an AttributeError that mentions monitoring, check python --version: anything older than 3.12 has no sys.monitoring.
Step 2: Claim a tool ID and expect a collision
The docs say that “Identifiers are integers in the range 0 to 5 inclusive” and that use_tool_id “Raises a ValueError if tool_id is in use.” Four of the six IDs have a conventional owner: 0 for a debugger, 1 for coverage, 2 for a profiler and 5 for an optimizer. The docs add that all IDs are treated the same by the interpreter, and that the predefined names exist “to make co-operation of tools easier”. This script claims ID 1 twice and prints who owns what.
# step02_tool_ids.py
import sys
mon = sys.monitoring
print("version:", sys.version.split()[0])
print("names before:", [mon.get_tool(i) for i in range(6)])
try:
mon.use_tool_id(mon.COVERAGE_ID, "my-tool")
except ValueError as exc:
print("claiming id 1 failed:", exc)
print("owner of id 1:", mon.get_tool(mon.COVERAGE_ID))
else:
print("claimed id 1 as my-tool")
try:
mon.use_tool_id(mon.COVERAGE_ID, "second-tool")
except ValueError as exc:
print("second claim failed:", exc)
mon.free_tool_id(mon.COVERAGE_ID)
print("names after free:", [mon.get_tool(i) for i in range(6)])
python step02_tool_ids.py
version: 3.13.14
names before: [None, None, None, None, None, None]
claimed id 1 as my-tool
second claim failed: tool 1 is already in use
names after free: [None, None, None, None, None, None]
The second claim fails with tool 1 is already in use, which is the guard rail working. Now run the same script under coverage.py using its sys.monitoring core. In PowerShell, set the environment variable first, as in the block below. In cmd.exe use set COVERAGE_CORE=sysmon, and in bash put COVERAGE_CORE=sysmon in front of the command.
$env:COVERAGE_CORE = "sysmon"
python -m coverage run --data-file=covdata.tmp step02_tool_ids.py
version: 3.13.14
names before: [None, 'coverage.py', None, None, None, None]
claiming id 1 failed: tool 1 is already in use
owner of id 1: coverage.py
coverage.py got there first and holds ID 1 under the name coverage.py, so your claim fails. This is not an exotic case. The coverage.py documentation describes the sysmon core as “Only available in Python 3.12+, and the default in Python 3.14+”, so on a current Python your tool will meet it as soon as someone runs your code under coverage run. The lesson for the finished tool: never assume that ID 1 is free. It will try 1, then 3, then 4, and say clearly when none is left.
Step 3: Version 1, record every line
Now the first real tool. Version 1 does the simplest thing that could work: for every LINE event it adds the pair (file name, line number) to a set and counts how often it was called.
# linecov_v1.py
import sys
mon = sys.monitoring
class LineCoverage:
"""Version 1: remember every (file, line) that runs, anywhere."""
def __init__(self, root):
self.root = root
self.tool_id = mon.COVERAGE_ID
self.hits = set()
self.callbacks = 0
def _on_line(self, code, line_number):
self.callbacks += 1
self.hits.add((code.co_filename, line_number))
def start(self):
mon.use_tool_id(self.tool_id, "linecov")
mon.register_callback(self.tool_id, mon.events.LINE, self._on_line)
mon.set_events(self.tool_id, mon.events.LINE)
def stop(self):
mon.set_events(self.tool_id, mon.events.NO_EVENTS)
mon.register_callback(self.tool_id, mon.events.LINE, None)
mon.free_tool_id(self.tool_id)
To compare versions fairly, every version gets the same driver. drive.py is a small program that calls the shop functions, including one that fails, and also imports the standard json module, so that there is some code that is not yours. step_variant.py takes the name of a version on the command line, starts it, imports and runs the driver, stops it and prints what it found. Note that the import happens after start(), so that the module-level lines (the def lines) are measured too.
# drive.py
import json
import shop
def run():
for sku, quantity, country in [("pen", "3", "US"), ("ink", "10", "US"), ("pad", "200", "CA")]:
shop.order_total(sku, quantity, country)
try:
shop.order_total("pen", "many")
except ValueError:
pass
return json.dumps({"ok": True})
# step_variant.py
import importlib
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
APP = os.path.join(HERE, "app")
sys.path.insert(0, APP)
name = sys.argv[1]
variant = importlib.import_module(name)
cov = variant.LineCoverage(APP)
cov.start()
import drive
drive.run()
cov.stop()
names = sorted({os.path.basename(path) for path, _ in cov.hits})
shop_lines = sorted(line for path, line in cov.hits if os.path.basename(path) == "shop.py")
print(f"{name}: {cov.callbacks} callbacks, {len(cov.hits)} (file, line) pairs recorded")
print("files recorded:", len(names), names[:6], "..." if len(names) > 6 else "")
print("shop.py lines recorded:", len(shop_lines))
python step_variant.py linecov_v1
linecov_v1: 30989 callbacks, 2915 (file, line) pairs recorded
files recorded: 25 ['<frozen _collections_abc>', '<frozen abc>', '<frozen importlib._bootstrap>', '<frozen importlib._bootstrap_external>', '<frozen zipimport>', '<string>'] ...
shop.py lines recorded: 28
We asked about one file, shop.py, and we got 25 files. Python’s import machinery (the <frozen importlib...> names) and the standard library modules that import json pulls in all ran under the tool, and the callback was called 30,989 times to record 2,915 pairs. The 28 lines of shop.py are in there, buried in noise. Remember these numbers. The exact callback counts differ a little between Python versions, and the next three versions will shrink them. If your first run shows a few hundred more callbacks, that is Python writing cache files for your new modules, so run the command a second time.
Step 4: Version 2, keep only your own files
Version 2 adds a filter. It remembers the root folder, and the callback records a line only when the file lives under it. Two details matter here and both come from real bugs. The root is stored with a trailing path separator, because without it a root of app would also match a sibling folder called app2. And both paths go through os.path.normcase, because Windows treats C:\Lab\App and c:\lab\app as the same folder while a Python string comparison does not.
# linecov_v2.py
import os
import sys
mon = sys.monitoring
class LineCoverage:
"""Version 2: keep only files under root, but still called on every line."""
def __init__(self, root):
self.root = os.path.normcase(os.path.abspath(root)).rstrip(os.sep) + os.sep
self.tool_id = mon.COVERAGE_ID
self.hits = set()
self.callbacks = 0
def _wanted(self, filename):
return os.path.normcase(filename).startswith(self.root)
def _on_line(self, code, line_number):
self.callbacks += 1
if self._wanted(code.co_filename):
self.hits.add((os.path.normcase(code.co_filename), line_number))
def start(self):
mon.use_tool_id(self.tool_id, "linecov")
mon.register_callback(self.tool_id, mon.events.LINE, self._on_line)
mon.set_events(self.tool_id, mon.events.LINE)
def stop(self):
mon.set_events(self.tool_id, mon.events.NO_EVENTS)
mon.register_callback(self.tool_id, mon.events.LINE, None)
mon.free_tool_id(self.tool_id)
python step_variant.py linecov_v2
linecov_v2: 30989 callbacks, 28 (file, line) pairs recorded
files recorded: 1 ['shop.py']
shop.py lines recorded: 28
The answer is clean now: one file, 28 lines. But look at the callback count. It has not changed. Filtering the answers did nothing for the questions: Python still called our function for every line of every file, thousands of times, and we threw most of them away.
Step 5: Version 3, say it once and return DISABLE
Here is the idea that makes sys.monitoring special. The docs describe DISABLE as “A special value that can be returned from a callback function to disable events for the current code location.” They also state that this “does not change which events are set, or any other code locations for the same event”, and that “Disabling events for specific locations is very important for high performance monitoring.” In other words, each line of code is its own switch, and returning DISABLE flips that one switch off.
For coverage this is perfect. The question is “did line 12 run at least once?”, and after the first yes there is nothing left to learn from line 12. Version 3 changes one line: the callback ends with return mon.DISABLE.
# linecov_v3.py
import os
import sys
mon = sys.monitoring
class LineCoverage:
"""Version 3: every location reports once, then DISABLE switches it off."""
def __init__(self, root):
self.root = os.path.normcase(os.path.abspath(root)).rstrip(os.sep) + os.sep
self.tool_id = mon.COVERAGE_ID
self.hits = set()
self.callbacks = 0
def _wanted(self, filename):
return os.path.normcase(filename).startswith(self.root)
def _on_line(self, code, line_number):
self.callbacks += 1
if self._wanted(code.co_filename):
self.hits.add((os.path.normcase(code.co_filename), line_number))
return mon.DISABLE
def start(self):
mon.use_tool_id(self.tool_id, "linecov")
mon.register_callback(self.tool_id, mon.events.LINE, self._on_line)
mon.set_events(self.tool_id, mon.events.LINE)
def stop(self):
mon.set_events(self.tool_id, mon.events.NO_EVENTS)
mon.register_callback(self.tool_id, mon.events.LINE, None)
mon.free_tool_id(self.tool_id)
python step_variant.py linecov_v3
linecov_v3: 3151 callbacks, 28 (file, line) pairs recorded
files recorded: 1 ['shop.py']
shop.py lines recorded: 28
Callbacks fell from 30,989 to 3,151, about ten times fewer, with the same 28 lines found. Why 3,151 and not 28? Because every distinct line of enum.py, the regular-expression parser and the import machinery still reports once before it is disabled. A line that runs a million times costs one callback; a line that runs once also costs one.
One honest limit: a disabled line is silent, so this design cannot tell you how many times a line ran. Coverage needs a yes or a no. A profiler that needs counts must keep its events on.
Step 6: Version 4, only ask about your own code
Version 3 still pays one callback for every line of the standard library. Version 4 removes that cost by never asking about those lines at all. The trick uses two kinds of event settings. Instead of turning LINE on globally, it turns on only PY_START, which fires each time a Python function starts. In that callback it looks at the function’s file. If the file is yours, set_local_events turns LINE on for that one code object. Either way it returns DISABLE, so a function reports its start only once.
# linecov_v4.py
import os
import sys
mon = sys.monitoring
class LineCoverage:
"""Version 4: ask for LINE events only on code objects under root."""
def __init__(self, root):
self.root = os.path.normcase(os.path.abspath(root)).rstrip(os.sep) + os.sep
self.tool_id = mon.COVERAGE_ID
self.hits = set()
self.callbacks = 0
self._watched = []
def _wanted(self, filename):
return os.path.normcase(filename).startswith(self.root)
def _on_start(self, code, instruction_offset):
self.callbacks += 1
if self._wanted(code.co_filename):
mon.set_local_events(self.tool_id, code, mon.events.LINE)
self._watched.append(code)
return mon.DISABLE
def _on_line(self, code, line_number):
self.callbacks += 1
self.hits.add((os.path.normcase(code.co_filename), line_number))
return mon.DISABLE
def start(self):
mon.use_tool_id(self.tool_id, "linecov")
mon.register_callback(self.tool_id, mon.events.PY_START, self._on_start)
mon.register_callback(self.tool_id, mon.events.LINE, self._on_line)
mon.set_events(self.tool_id, mon.events.PY_START)
def stop(self):
mon.set_events(self.tool_id, mon.events.NO_EVENTS)
for code in self._watched:
mon.set_local_events(self.tool_id, code, mon.events.NO_EVENTS)
mon.register_callback(self.tool_id, mon.events.PY_START, None)
mon.register_callback(self.tool_id, mon.events.LINE, None)
mon.free_tool_id(self.tool_id)
python step_variant.py linecov_v4
linecov_v4: 288 callbacks, 28 (file, line) pairs recorded
files recorded: 1 ['shop.py']
shop.py lines recorded: 28
288 callbacks, with the same 28 lines. Every distinct line reports at most once, so exactly 28 of the 288 are LINE reports; the other 260 are one-time PY_START reports, one per function that started, in any file.
Notice the extra work in stop(): it walks the list of watched code objects and clears their local events. Step 10 shows why that matters on older Pythons.
The catch: the function that called start()
Version 4 has a hole. PY_START fires when a function starts, so a function that is already running when you call start() never reports it. Usually that is a launcher script outside the measured folder and nobody notices. But if the code that calls start() is itself inside the measured root, its remaining lines vanish. This script makes its own folder the root, runs a few lines after start(), and prints which of its own lines were recorded.
# step_gap.py
import importlib
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
name = sys.argv[1]
cov = importlib.import_module(name).LineCoverage(HERE)
cov.start()
total = 0
for number in range(3):
total += number
cov.stop()
hits = cov.hits
mine = sorted(line for path, line in (hits if isinstance(hits, set) else hits.keys())
if path.endswith("step_gap.py"))
print(f"{name}: lines of this very file that were recorded: {mine}")
python step_gap.py linecov_v3
python step_gap.py linecov_v4
linecov_v3: lines of this very file that were recorded: [11, 12, 13, 14]
linecov_v4: lines of this very file that were recorded: []
Version 3 saw lines 11 to 14 of the script. Version 4 saw nothing. The finished tool fixes this by walking the call stack when it starts and switching LINE on for every in-scope frame that is already running. Step 7 builds it and runs this same script again.
The four versions side by side
Counts from the runs above, Python 3.13.14:
| Version | What changed | Callbacks | Pairs recorded |
|---|---|---|---|
| 1 | record every line everywhere | 30,989 | 2,915 |
| 2 | keep only files under the root | 30,989 | 28 |
| 3 | return DISABLE after the first report |
3,151 | 28 |
| 4 | ask for LINE only on your own code objects |
288 | 28 |
Step 7: The finished tool, a report and a command line
The finished tool is version 4 plus the pieces that make it usable. Here is the whole file, then each piece explained.
# linecov.py
"""linecov: a small line-coverage tool built on sys.monitoring (Python 3.12 or newer)."""
import ast
import os
import runpy
import sys
import types
mon = sys.monitoring
CANDIDATE_IDS = (mon.COVERAGE_ID, 3, 4)
def claim_tool_id(name):
for tool_id in CANDIDATE_IDS:
if mon.get_tool(tool_id) is None:
mon.use_tool_id(tool_id, name)
return tool_id
owners = [mon.get_tool(tool_id) for tool_id in CANDIDATE_IDS]
raise RuntimeError(f"no free sys.monitoring tool id, owners: {owners}")
class LineCoverage:
def __init__(self, root):
self.root = os.path.normcase(os.path.abspath(root)).rstrip(os.sep) + os.sep
self.tool_id = None
self.hits = {}
self.context = ""
self.callbacks = 0
self._watched = {}
def _wanted(self, filename):
return os.path.normcase(filename).startswith(self.root)
def _watch(self, code):
mon.set_local_events(self.tool_id, code, mon.events.LINE)
self._watched[id(code)] = code
def _on_start(self, code, instruction_offset):
self.callbacks += 1
if self._wanted(code.co_filename):
self._watch(code)
return mon.DISABLE
def _on_line(self, code, line_number):
self.callbacks += 1
key = (os.path.normcase(code.co_filename), line_number)
self.hits.setdefault(key, set()).add(self.context)
return mon.DISABLE
def start(self):
if self.tool_id is not None:
raise RuntimeError("linecov is already started")
self.tool_id = claim_tool_id("linecov")
mon.register_callback(self.tool_id, mon.events.PY_START, self._on_start)
mon.register_callback(self.tool_id, mon.events.LINE, self._on_line)
mon.set_events(self.tool_id, mon.events.PY_START)
frame = sys._getframe(1)
while frame is not None:
if self._wanted(frame.f_code.co_filename):
self._watch(frame.f_code)
frame = frame.f_back
def stop(self):
if self.tool_id is None:
return
mon.set_events(self.tool_id, mon.events.NO_EVENTS)
for code in self._watched.values():
mon.set_local_events(self.tool_id, code, mon.events.NO_EVENTS)
mon.register_callback(self.tool_id, mon.events.PY_START, None)
mon.register_callback(self.tool_id, mon.events.LINE, None)
mon.free_tool_id(self.tool_id)
self.tool_id = None
self._watched.clear()
def switch_context(self, name):
self.context = name
mon.restart_events()
def lines_run(self, path):
key = os.path.normcase(os.path.abspath(path))
return {line for (name, line) in self.hits if name == key}
def contexts_for(self, path, line):
key = (os.path.normcase(os.path.abspath(path)), line)
return sorted(self.hits.get(key, set()) - {""})
def docstring_lines(tree):
lines = set()
for node in ast.walk(tree):
if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
first = node.body[0] if node.body else None
if isinstance(first, ast.Expr) and isinstance(first.value, ast.Constant) and isinstance(first.value.value, str):
lines.update(range(first.lineno, first.end_lineno + 1))
return lines
def executable_lines(path):
with open(path, encoding="utf-8") as handle:
source = handle.read()
lines = set()
pending = [compile(source, path, "exec")]
while pending:
code = pending.pop()
lines.update(line for _, _, line in code.co_lines() if line is not None)
pending.extend(c for c in code.co_consts if isinstance(c, types.CodeType))
lines.discard(0)
return lines - docstring_lines(ast.parse(source))
def ranges(numbers):
numbers = sorted(numbers)
parts = []
i = 0
while i < len(numbers):
j = i
while j + 1 < len(numbers) and numbers[j + 1] == numbers[j] + 1:
j += 1
parts.append(str(numbers[i]) if i == j else f"{numbers[i]}-{numbers[j]}")
i = j + 1
return ", ".join(parts)
def report(cov, out=sys.stdout):
names = sorted({name for name, _ in cov.hits})
print(f"{'Name':<14}{'Stmts':>6}{'Miss':>6}{'Cover':>7} Missing", file=out)
total = missed_total = 0
for name in names:
executable = executable_lines(name)
ran = cov.lines_run(name)
missing = executable - ran
total += len(executable)
missed_total += len(missing)
cover = 100 * (len(executable) - len(missing)) / len(executable)
short = os.path.relpath(name, cov.root)
print(f"{short:<14}{len(executable):>6}{len(missing):>6}{cover:>6.0f}% {ranges(missing)}", file=out)
if total:
print(f"{'TOTAL':<14}{total:>6}{missed_total:>6}{100 * (total - missed_total) / total:>6.0f}%", file=out)
def main(argv):
root = "."
while argv and argv[0] == "--root":
root, argv = argv[1], argv[2:]
if not argv:
print("usage: covrun.py [--root DIR] (-m MODULE | SCRIPT) [ARGS...]")
return 2
cov = LineCoverage(root)
status = 0
cov.start()
try:
if argv[0] == "-m":
sys.argv = [argv[1]] + argv[2:]
runpy.run_module(argv[1], run_name="__main__", alter_sys=True)
else:
sys.argv = argv
runpy.run_path(argv[0], run_name="__main__")
except SystemExit as exc:
status = exc.code if isinstance(exc.code, int) else int(bool(exc.code))
finally:
cov.stop()
report(cov)
return status
The finished tool, piece by piece
Claiming an ID politely
claim_tool_id tries ID 1 first, then 3 and 4, and raises an error that names the current owners when all three are busy. It avoids 0, 2 and 5 because those belong by convention to debuggers, profilers and optimizers.
Watching already-running code
start() ends with a loop over sys._getframe(1) and its f_back chain. Each frame whose file is under the root gets LINE events switched on right away, which closes the hole from step 6. sys._getframe is a CPython-specific function, so a tool for other interpreters would need another way to find running frames.
Stopping cleanly
stop() undoes everything it did: global events off, local events off for every watched code object, both callbacks unregistered, the ID freed. Code objects are tracked in a dictionary keyed by id(code) because two different functions can compile to code objects that compare equal.
The denominator
Coverage is a fraction, and the bottom of it is the number of executable lines. executable_lines compiles the file, walks every nested code object and collects the line numbers from co_lines(). The data model docs say each item is a (start, end, lineno) tuple, and that lineno is None “if the bytecodes in the given range have no line number”. Two lines needed special handling, which the cross-check later proves: line 0, which the module’s first bookkeeping instruction (RESUME) carries, and the module docstring.
Contexts
switch_context(name) records which test is running and calls mon.restart_events(). Step 8 explains why that call is essential.
Close the hole from step 6
The finished tool seeds the frames that are already running, so the gap script should now behave like version 3.
python step_gap.py linecov
linecov: lines of this very file that were recorded: [11, 12, 13, 14]
Run it on the test suite
covrun.py is a tiny launcher. It must be a separate file, so that linecov is imported as a normal module.
# covrun.py
import sys
import linecov
sys.exit(linecov.main(sys.argv[1:]))
python covrun.py --root app -m pytest -q tests/test_shop.py
... [100%]
3 passed in 0.01s
Name Stmts Miss Cover Missing
shop.py 29 5 83% 11, 22, 31-33
TOTAL 29 5 83%
The tool ran pytest inside the same process, with linecov watching, and printed what the three tests never reached. Open app/shop.py and compare. Line 11 is the raise for a quantity of zero. Line 22 is return 20, the 20 percent discount. Lines 31 to 33 are the Canadian and international shipping branches. These are exactly the lines our three tests skip. Close the gap with four more test cases.
# tests/test_shop_more.py
import pytest
import shop
def test_zero_quantity_is_refused():
with pytest.raises(ValueError, match="at least 1"):
shop.parse_quantity("0")
def test_a_hundred_pens_get_twenty_percent_off():
assert shop.discount_percent(100) == 20
@pytest.mark.parametrize("country, cents", [("CA", 899), ("DE", 1999)])
def test_shipping_outside_the_us(country, cents):
assert shop.shipping_cents(1000, country) == cents
python covrun.py --root app -m pytest -q
....... [100%]
7 passed in 0.01s
Name Stmts Miss Cover Missing
shop.py 29 0 100%
TOTAL 29 0 100%
100 percent, and the “Missing” column is empty. Remember that this proves the lines ran, not that the assertions are good. Coverage finds code that nobody exercises; it cannot judge whether a test would notice a wrong answer.
Check the answers against two independent tools
A coverage tool that is fast but wrong is worse than none. This script runs the same three tests under four collectors: linecov, a pure-Python sys.settrace tracer, and coverage.py with its C tracer and with its sysmon core. It compares the sets of lines that ran, and then compares our executable-line list with coverage.py’s list of statements.
# crosscheck.py
import os
import sys
import coverage
import linecov
HERE = os.path.dirname(os.path.abspath(__file__))
APP = os.path.join(HERE, "app")
SHOP = os.path.join(APP, "shop.py")
KEY = os.path.normcase(SHOP)
sys.path[:0] = [APP, os.path.join(HERE, "tests")]
def run_suite():
sys.modules.pop("shop", None)
sys.modules.pop("test_shop", None)
import test_shop
test_shop.test_small_order_pays_shipping()
test_shop.test_ten_inks_get_ten_percent_off()
test_shop.test_bad_quantity_is_refused()
def with_linecov():
cov = linecov.LineCoverage(APP)
cov.start()
run_suite()
cov.stop()
return cov.lines_run(SHOP)
def with_settrace():
seen = set()
def local(frame, event, arg):
if event == "line":
seen.add(frame.f_lineno)
return local
def outer(frame, event, arg):
return local if os.path.normcase(frame.f_code.co_filename) == KEY else None
sys.settrace(outer)
run_suite()
sys.settrace(None)
return seen
def with_coverage_py(core):
os.environ["COVERAGE_CORE"] = core
cov = coverage.Coverage(source=[APP], data_file=None, config_file=False)
cov.start()
run_suite()
cov.stop()
ran = set(cov.get_data().lines(SHOP))
statements = set(cov.analysis2(SHOP)[1])
return ran, statements
ours = with_linecov()
traced = with_settrace()
ran_c, statements = with_coverage_py("ctrace")
ran_s, _ = with_coverage_py("sysmon")
print("lines of shop.py that ran:")
for name, lines in [("linecov", ours), ("settrace", traced), ("coverage.py ctrace", ran_c), ("coverage.py sysmon", ran_s)]:
print(f" {name:<20}{len(lines):>3} lines same as linecov: {lines == ours}")
raw = set()
pending = [compile(open(SHOP, encoding="utf-8").read(), SHOP, "exec")]
while pending:
code = pending.pop()
raw.update(line for _, _, line in code.co_lines() if line is not None)
pending.extend(c for c in code.co_consts if hasattr(c, "co_lines"))
print("executable lines, co_lines walk:", len(raw), "| coverage.py statements:", len(statements))
print("only in the co_lines walk:", sorted(raw - statements))
print("only in coverage.py:", sorted(statements - raw))
print("linecov.executable_lines equals coverage.py statements:", linecov.executable_lines(SHOP) == statements)
python crosscheck.py
lines of shop.py that ran:
linecov 25 lines same as linecov: True
settrace 25 lines same as linecov: True
coverage.py ctrace 25 lines same as linecov: True
coverage.py sysmon 25 lines same as linecov: True
executable lines, co_lines walk: 31 | coverage.py statements: 29
only in the co_lines walk: [0, 2]
only in coverage.py: []
linecov.executable_lines equals coverage.py statements: True
All four collectors agree on the 25 lines of shop.py that ran. The denominators disagreed at first: a plain walk of co_lines() found 31 lines against coverage.py’s 29, and the two extra lines were 0 and 2. Line 0 is bookkeeping, and line 2 is the module docstring (line 1 is the file-name comment), which coverage.py does not count as a statement. After executable_lines dropped both, the last line prints True. The same check on Python 3.15.2 printed identical results.
Step 8: Find out which test ran which line
A coverage number says what ran. A context says who ran it, and that answers questions such as “which tests do I need to rerun after I change line 30?” The tool keeps a set of context names for every line, and switch_context changes the current name. The script below runs the three original tests directly, naming the context after each test, and does it twice: once with the real switch_context and once with a naive version that only changes the name.
# step_contexts.py
import os
import sys
import linecov
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path[:0] = [os.path.join(HERE, "app"), os.path.join(HERE, "tests")]
import test_shop
SHOP = os.path.join(HERE, "app", "shop.py")
TESTS = [
test_shop.test_small_order_pays_shipping,
test_shop.test_ten_inks_get_ten_percent_off,
test_shop.test_bad_quantity_is_refused,
]
def run(restart):
cov = linecov.LineCoverage(os.path.join(HERE, "app"))
if not restart:
cov.switch_context = lambda name: setattr(cov, "context", name)
cov.start()
for test in TESTS:
cov.switch_context(test.__name__)
test()
cov.stop()
return cov
for restart in (True, False):
cov = run(restart)
label = "with restart_events() " if restart else "without restart_events()"
print(f"{label} line 6 (text.strip()) ran in: {cov.contexts_for(SHOP, 6)}")
print(f"{label} line 30 (US shipping) ran in: {cov.contexts_for(SHOP, 30)}")
python step_contexts.py
with restart_events() line 6 (text.strip()) ran in: ['test_bad_quantity_is_refused', 'test_small_order_pays_shipping', 'test_ten_inks_get_ten_percent_off']
with restart_events() line 30 (US shipping) ran in: ['test_small_order_pays_shipping', 'test_ten_inks_get_ten_percent_off']
without restart_events() line 6 (text.strip()) ran in: ['test_small_order_pays_shipping']
without restart_events() line 30 (US shipping) ran in: ['test_small_order_pays_shipping']
With restart_events(), line 6 (text = text.strip()) is credited to all three tests and line 30 to the two tests that reach US shipping. Without it, both lines are credited only to the first test that ran them. The reason is the DISABLE from step 5: once a line has reported, it stays silent, so a later test that runs the same line is never told about. The docs describe restart_events as: “Enable all the events that were disabled by sys.monitoring.DISABLE for all tools.” Each test then pays one fresh callback per line it touches, which is cheap, but note the words for all tools: a debugger sharing the interpreter would also get its disabled locations re-armed.
This is also an area where building your own tool shows how much a mature one does. The coverage.py documentation warns that “The sysmon core does not yet support plugins, dynamic contexts, or some concurrency libraries.”
Step 9: Measure the cost
Now the claim that started the whole post. The benchmark runs each variant in a fresh Python process, five times, and reports the median. Two workloads are used. loops is a hot, CPU-bound loop of 1,500,000 iterations plus 15,000 Fraction additions from the standard library. pytest is a tiny real test session run in-process. The tool is started before the timer and stopped after it, so the numbers show the cost of running under the tool, not the cost of starting it.
# app/workload.py
from fractions import Fraction
def checksum(n):
total = 0
for i in range(n):
if i % 3 == 0:
total += i * 2
elif i % 5 == 0:
total -= i
else:
total ^= i
return total
def exact_mean(count):
acc = Fraction(0)
for i in range(count):
acc += Fraction(i, 7)
return acc / count
def run():
return checksum(1_500_000), exact_mean(15_000)
# bench_child.py
import contextlib
import importlib
import io
import json
import os
import sys
import time
HERE = os.path.dirname(os.path.abspath(__file__))
APP = os.path.join(HERE, "app")
sys.path.insert(0, HERE)
sys.path.insert(0, APP)
variant, workload = sys.argv[1], sys.argv[2]
ROOT = os.path.normcase(os.path.abspath(APP)).rstrip(os.sep) + os.sep
class SetTraceTool:
"""The classic way: a Python function called by sys.settrace."""
def __init__(self, root):
self.hits = set()
self.callbacks = 0
def _local(self, frame, event, arg):
self.callbacks += 1
if event == "line":
self.hits.add((os.path.normcase(frame.f_code.co_filename), frame.f_lineno))
return self._local
def _global(self, frame, event, arg):
self.callbacks += 1
if os.path.normcase(frame.f_code.co_filename).startswith(ROOT):
return self._local
return None
def start(self):
sys.settrace(self._global)
def stop(self):
sys.settrace(None)
class CoveragePyTool:
"""coverage.py in-process; the measurement core comes from COVERAGE_CORE."""
def __init__(self, root):
import coverage
self.cov = coverage.Coverage(source=[root], data_file=None, config_file=False)
self.hits = set()
self.callbacks = 0
def start(self):
self.cov.start()
def stop(self):
self.cov.stop()
data = self.cov.get_data()
for name in data.measured_files():
for line in data.lines(name) or []:
self.hits.add((os.path.normcase(name), line))
class NoTool:
hits = set()
callbacks = 0
def __init__(self, root):
pass
def start(self):
pass
def stop(self):
pass
def make_tool():
if variant == "none":
return NoTool(APP)
if variant == "settrace":
return SetTraceTool(APP)
if variant.startswith("cov-"):
return CoveragePyTool(APP)
return importlib.import_module("linecov_" + variant).LineCoverage(APP)
if workload == "loops":
import workload as target
def job():
target.run()
else:
import pytest
def job():
with contextlib.redirect_stdout(io.StringIO()):
code = pytest.main(["-q", "--no-header", "tests/test_shop.py"])
assert code == 0
tool = make_tool()
tool.start()
began = time.perf_counter()
job()
seconds = time.perf_counter() - began
tool.stop()
in_scope = sum(1 for path, _ in tool.hits if os.path.normcase(path).startswith(ROOT))
print(json.dumps({"seconds": round(seconds, 4), "callbacks": tool.callbacks, "lines": in_scope}))
# bench.py
import json
import os
import statistics
import subprocess
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
workload = sys.argv[1]
repeats = int(sys.argv[2])
variants = sys.argv[3:] or ["none", "settrace", "v1", "v2", "v3", "v4", "cov-ctrace", "cov-sysmon"]
print(f"python {sys.version.split()[0]}, workload {workload}, median of {repeats} fresh processes")
print(f"{'variant':<11} {'seconds':>8} {'x none':>7} {'callbacks':>10} {'lines in app':>13}")
baseline = None
for variant in variants:
env = dict(os.environ)
if variant.startswith("cov-"):
env["COVERAGE_CORE"] = variant.split("-", 1)[1]
runs = []
for _ in range(repeats):
done = subprocess.run(
[sys.executable, os.path.join(HERE, "bench_child.py"), variant, workload],
capture_output=True, text=True, cwd=HERE, env=env,
)
if done.returncode != 0:
print(variant, "FAILED:", done.stderr.strip()[-300:])
break
runs.append(json.loads(done.stdout.strip().splitlines()[-1]))
if not runs:
continue
seconds = statistics.median(r["seconds"] for r in runs)
if variant == "none":
baseline = seconds
ratio = f"{seconds / baseline:.2f}" if baseline else "-"
print(f"{variant:<11} {seconds:>8.3f} {ratio:>7} {runs[0]['callbacks']:>10} {runs[0]['lines']:>13}")
python bench.py loops 5
python bench.py pytest 5
Results on Python 3.13.14
python 3.13.14, workload loops, median of 5 fresh processes
variant seconds x none callbacks lines in app
none 0.070 1.00 0 0
settrace 2.628 37.81 5590022 13
v1 0.514 7.40 5917902 13
v2 4.652 66.93 5917902 13
v3 0.068 0.97 70 13
v4 0.070 1.01 27 13
cov-ctrace 0.152 2.19 0 13
cov-sysmon 0.075 1.08 0 13
python 3.13.14, workload pytest, median of 5 fresh processes
variant seconds x none callbacks lines in app
none 0.049 1.00 0 0
settrace 0.090 1.84 66901 25
v1 0.087 1.76 329131 25
v2 0.186 3.79 328980 25
v3 0.059 1.20 11688 25
v4 0.051 1.03 1482 25
cov-ctrace 0.099 2.02 0 25
cov-sysmon 0.085 1.73 0 25
The table has five lessons.
- A Python function on every line is expensive. The
sys.settracetracer made the hot loop 37.8 times slower, with 5.59 million calls. - Cheaper callbacks help, but only so much. Version 1 makes about as many calls as the tracer but is 7.4 times slower rather than 37.8, because its callback only adds to a set.
- Doing real work in the callback is costly. Version 2 is the slowest row at 66.9 times. By my arithmetic its callback costs about 0.77 microseconds, against 0.08 for version 1, because it normalizes and compares paths on every single call.
DISABLEis the big win. Versions 3 and 4 made 70 and 27 callbacks for this workload and take 0.97 and 1.01 times as long as no tool at all, which is within the noise of the measurement.- Scoping matters when other people’s code is large. In the pytest session, version 3 costs 20 percent more than no tool, because it pays a callback for each new line in pytest itself. Version 4 costs 3 percent.
For comparison, coverage.py’s C tracer ran the hot loop at 2.19 times and its sysmon core at 1.08 times. That is not a verdict on coverage.py: the setup here uses data_file=None and does no file output, and coverage.py also handles branches, plugins, parallel runs and reporting, none of which our small tool does.
The same benchmark on Python 3.15.2
| Variant | Loops 3.13.14 | Loops 3.15.2 | pytest 3.13.14 | pytest 3.15.2 |
|---|---|---|---|---|
| sys.settrace tracer | 37.81 | 41.11 | 1.84 | 1.71 |
| version 1 | 7.40 | 6.89 | 1.76 | 1.59 |
| version 2 | 66.93 | 75.37 | 3.79 | 3.36 |
| version 3 | 0.97 | 1.00 | 1.20 | 1.20 |
| version 4 | 1.01 | 1.00 | 1.03 | 1.04 |
| coverage.py ctrace | 2.19 | 2.46 | 2.02 | 1.89 |
| coverage.py sysmon | 1.08 | 1.02 | 1.73 | 1.61 |
Every number is the median time with the tool divided by the median time without it, so 1.00 means no measurable cost. The pattern holds on both versions. The baselines differ (0.070 and 0.062 seconds for the loops, 0.049 and 0.083 for the pytest session), so compare ratios, not seconds. These figures come from one Windows machine, and the short pytest session is dominated by one-time start-up work, so treat the second workload as a rough guide.
Step 10: Traps worth knowing before you ship a tool
Trap 1: free_tool_id used to leave things behind
This script gives ID 3 to a first tool that sets a callback and local events, frees the ID, hands it to a second tool, and counts how many events still reach the first tool’s callback after the second tool has taken the ID.
# step_free.py
import sys
mon = sys.monitoring
TOOL = 3
seen = []
def on_line(code, line_number):
seen.append(line_number)
def target():
first = 1
return first
mon.use_tool_id(TOOL, "first-tool")
mon.register_callback(TOOL, mon.events.LINE, on_line)
mon.set_local_events(TOOL, target.__code__, mon.events.LINE)
target()
print("events while the first tool owned the id:", len(seen))
mon.free_tool_id(TOOL)
mon.use_tool_id(TOOL, "second-tool")
target()
print("events after free_tool_id and a new owner:", len(seen) - 2)
print("python", sys.version.split()[0])
python step_free.py
events while the first tool owned the id: 2
events after free_tool_id and a new owner: 2
python 3.13.14
That is the output on Python 3.13.14: the first tool’s callback and local events were still active under an ID that now belonged to someone else. On Python 3.15.2 the same script prints 0 for the second line. The docs explain the difference: in 3.14, free_tool_id “Now calls clear_tool_id() before releasing tool_id”, whereas before it did not disable local events or unregister callbacks. If you support 3.12 or 3.13, do the clean-up yourself, as stop() does.
Trap 2: errors in your callback surface in the monitored code
If a callback raises, the exception appears in the program being measured, at the spot where the event fired. That is useful while you develop the tool and dangerous in production, so a real tool decides deliberately whether to catch and log such errors.
Trap 3: threads are seen, other processes are not
PEP 669 states that “events and callbacks are per interpreter, not per thread”, so code on any thread is recorded. A child process is a brand new interpreter, and your tool is not running in it. The next script checks both, and also runs sys.settrace side by side with the tool. The PEP says that sys.settrace() and sys.setprofile() “will act as if they were tools 6 and 7 respectively, so can be used alongside this PEP.”
# step_gotchas.py
import multiprocessing
import os
import sys
import threading
import linecov
HERE = os.path.dirname(os.path.abspath(__file__))
APP = os.path.join(HERE, "app")
sys.path.insert(0, APP)
import shop
mon = sys.monitoring
def check_threads_and_processes():
cov = linecov.LineCoverage(APP)
cov.start()
worker = threading.Thread(target=shop.shipping_cents, args=(100, "CA"))
worker.start()
worker.join()
child = multiprocessing.Process(target=shop.shipping_cents, args=(100, "XX"))
child.start()
child.join()
cov.stop()
ran = cov.lines_run(os.path.join(APP, "shop.py"))
print("line 32 ran in a thread, recorded:", 32 in ran)
print("line 33 ran in a child process, recorded:", 33 in ran)
def check_settrace_together():
seen_by_settrace = set()
def local(frame, event, arg):
if event == "line":
seen_by_settrace.add(frame.f_lineno)
return local
def outer(frame, event, arg):
return local if frame.f_code.co_name == "discount_percent" else None
cov = linecov.LineCoverage(APP)
cov.start()
sys.settrace(outer)
shop.discount_percent(500)
sys.settrace(None)
cov.stop()
both = cov.lines_run(os.path.join(APP, "shop.py")) >= {21, 22}
print("settrace saw lines:", sorted(seen_by_settrace), "| linecov saw lines 21 and 22:", both)
def check_callback_errors():
def broken(code, line_number):
raise RuntimeError("callback bug")
tool_id = linecov.claim_tool_id("broken-tool")
mon.register_callback(tool_id, mon.events.LINE, broken)
mon.set_local_events(tool_id, shop.unit_price.__code__, mon.events.LINE)
try:
shop.unit_price("pen")
except RuntimeError as exc:
print("the error came out of shop.unit_price:", exc)
mon.set_local_events(tool_id, shop.unit_price.__code__, mon.events.NO_EVENTS)
mon.register_callback(tool_id, mon.events.LINE, None)
mon.free_tool_id(tool_id)
if __name__ == "__main__":
check_threads_and_processes()
check_settrace_together()
check_callback_errors()
python step_gotchas.py
line 32 ran in a thread, recorded: True
line 33 ran in a child process, recorded: False
settrace saw lines: [21, 22] | linecov saw lines 21 and 22: True
the error came out of shop.unit_price: callback bug
Line 32 ran in a worker thread and was recorded. Line 33 ran in a child process and was not. sys.settrace and the tool saw the same two lines at the same time. The last line is the broken callback from trap 2: its RuntimeError came out of shop.unit_price.
Trap 4: a disabled line has no count
Said once in step 5, worth repeating: if you need hit counts, durations or call counts, you cannot return DISABLE for those events. Pick the events you need and pay for them.
Step 11: Test the tool and plant bugs to see who notices
A coverage tool is a measuring instrument, so it deserves tests of its own. The suite below builds a small fixture module in a temporary folder and checks the behaviour we have been discussing: lines found, hot loops reporting once, out-of-scope code ignored, the sibling-folder prefix trap, Windows path case, a clean stop(), the fallback ID, the watched caller, contexts, threads, the denominator and the report. It is the longest file in the post, so it sits at the end.
# tooltests/test_linecov.py
import importlib.util
import inspect
import io
import os
import sys
import textwrap
import threading
import pytest
import linecov
mon = sys.monitoring
SOURCE = textwrap.dedent('''\
"""fixture module"""
def pick(flag):
if flag:
return "yes"
return "no"
def loop(n):
total = 0
for i in range(n):
total += i
return total
''')
def write_module(folder, name="fixture_mod.py"):
folder.mkdir(exist_ok=True)
path = folder / name
path.write_text(SOURCE, encoding="utf-8", newline="\n")
return str(path)
def load(path):
spec = importlib.util.spec_from_file_location("fixture_mod", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
@pytest.fixture
def app(tmp_path):
return tmp_path / "app"
def test_records_the_lines_that_ran(app):
path = write_module(app)
cov = linecov.LineCoverage(app)
cov.start()
load(path).pick(True)
cov.stop()
ran = cov.lines_run(path)
assert {5, 6} <= ran
assert 7 not in ran
def test_a_hot_loop_reports_each_line_once(app):
path = write_module(app)
cov = linecov.LineCoverage(app)
cov.start()
load(path).loop(1000)
cov.stop()
assert 13 in cov.lines_run(path)
assert cov.callbacks < 40
def test_each_function_reports_its_start_once(app):
path = write_module(app)
cov = linecov.LineCoverage(app)
cov.start()
module = load(path)
for _ in range(500):
module.pick(True)
cov.stop()
assert cov.callbacks < 40
def test_code_outside_the_root_is_ignored(app):
import json
cov = linecov.LineCoverage(app)
cov.start()
json.dumps({"a": [1, 2, 3]})
cov.stop()
assert cov.hits == {}
def test_a_sibling_folder_with_the_same_prefix_is_ignored(tmp_path):
inside = write_module(tmp_path / "app")
outside = write_module(tmp_path / "app2")
cov = linecov.LineCoverage(tmp_path / "app")
cov.start()
load(inside).pick(True)
load(outside).pick(True)
cov.stop()
assert cov.lines_run(inside)
assert cov.lines_run(outside) == set()
@pytest.mark.skipif(os.name != "nt", reason="Windows paths ignore case")
def test_the_spelling_of_the_root_does_not_matter(app):
path = write_module(app)
cov = linecov.LineCoverage(str(app).upper())
cov.start()
load(path).pick(True)
cov.stop()
assert cov.lines_run(path)
def test_stop_frees_the_id_and_leaves_no_events_behind(app):
path = write_module(app)
cov = linecov.LineCoverage(app)
cov.start()
tool_id = cov.tool_id
module = load(path)
module.pick(True)
cov.stop()
assert mon.get_tool(tool_id) is None
seen = []
mon.use_tool_id(tool_id, "next-owner")
try:
mon.register_callback(tool_id, mon.events.LINE, lambda code, line: seen.append(line))
module.pick(False)
finally:
mon.register_callback(tool_id, mon.events.LINE, None)
mon.free_tool_id(tool_id)
assert seen == []
def test_start_twice_is_refused(app):
cov = linecov.LineCoverage(app)
cov.start()
try:
with pytest.raises(RuntimeError):
cov.start()
finally:
cov.stop()
def test_it_takes_another_id_when_the_usual_one_is_busy(app):
mon.use_tool_id(mon.COVERAGE_ID, "someone-else")
cov = linecov.LineCoverage(app)
try:
cov.start()
assert cov.tool_id == 3
cov.stop()
finally:
mon.free_tool_id(mon.COVERAGE_ID)
def test_it_says_so_when_every_id_is_busy(app):
taken = []
try:
for tool_id in linecov.CANDIDATE_IDS:
mon.use_tool_id(tool_id, "busy")
taken.append(tool_id)
with pytest.raises(RuntimeError, match="no free"):
linecov.LineCoverage(app).start()
finally:
for tool_id in taken:
mon.free_tool_id(tool_id)
def test_the_function_that_called_start_is_watched():
cov = linecov.LineCoverage(os.path.dirname(os.path.abspath(__file__)))
cov.start()
marker = inspect.currentframe().f_lineno + 1
total = sum([1, 2, 3])
cov.stop()
assert total == 6
assert marker in cov.lines_run(__file__)
def test_switch_context_credits_every_test(app):
path = write_module(app)
cov = linecov.LineCoverage(app)
cov.start()
module = load(path)
for name in ("first", "second"):
cov.switch_context(name)
module.pick(True)
cov.stop()
assert cov.contexts_for(path, 6) == ["first", "second"]
def test_threads_are_recorded(app):
path = write_module(app)
cov = linecov.LineCoverage(app)
cov.start()
module = load(path)
worker = threading.Thread(target=module.pick, args=(False,))
worker.start()
worker.join()
cov.stop()
assert 7 in cov.lines_run(path)
def test_executable_lines_skip_the_docstring_and_line_zero(app):
path = write_module(app)
assert linecov.executable_lines(path) == {4, 5, 6, 7, 10, 11, 12, 13, 14}
def test_the_report_names_the_missing_lines(app):
path = write_module(app)
cov = linecov.LineCoverage(app)
cov.start()
load(path).pick(True)
cov.stop()
out = io.StringIO()
linecov.report(cov, out)
text = out.getvalue()
assert "fixture_mod.py" in text
assert "7, 11-14" in text
assert "44%" in text
@pytest.mark.parametrize(
"numbers, expected",
[([], ""), ([5], "5"), ([3, 1, 2], "1-3"), ([1, 2, 3, 7, 9, 10], "1-3, 7, 9-10")],
)
def test_ranges(numbers, expected):
assert linecov.ranges(numbers) == expected
python -m pytest -q tooltests
................... [100%]
19 passed in 0.10s
Passing tests only prove that they agree with the code. To see whether they would catch a mistake, mutants.py copies linecov.py, plants one bug at a time and runs the suite against each copy. A planted bug that fails no test is a gap in the tests.
# mutants.py
import os
import re
import shutil
import subprocess
import sys
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
SOURCE = open(os.path.join(HERE, "linecov.py"), encoding="utf-8").read()
MUTANTS = [
("root without a trailing separator",
"os.path.abspath(root)).rstrip(os.sep) + os.sep", "os.path.abspath(root)).rstrip(os.sep)"),
("path case not normalized in _wanted",
"return os.path.normcase(filename).startswith(self.root)", "return filename.startswith(self.root)"),
("line callback forgets DISABLE",
"self.hits.setdefault(key, set()).add(self.context)\n return mon.DISABLE",
"self.hits.setdefault(key, set()).add(self.context)"),
("start callback forgets DISABLE",
" self._watch(code)\n return mon.DISABLE", " self._watch(code)"),
("stop leaves local events on",
" for code in self._watched.values():\n mon.set_local_events(self.tool_id, code, mon.events.NO_EVENTS)\n", ""),
("stop never frees the tool id",
" mon.free_tool_id(self.tool_id)\n", ""),
("running frames are not watched",
" if self._wanted(frame.f_code.co_filename):\n self._watch(frame.f_code)\n frame = frame.f_back",
" frame = frame.f_back"),
("switch_context forgets restart_events",
" self.context = name\n mon.restart_events()", " self.context = name"),
("docstring lines stay in the denominator",
"return lines - docstring_lines(ast.parse(source))", "return lines"),
("line zero stays in the denominator",
" lines.discard(0)\n", ""),
("ranges merge a gap of two",
"numbers[j + 1] == numbers[j] + 1", "numbers[j + 1] <= numbers[j] + 2"),
("no fallback tool id",
"CANDIDATE_IDS = (mon.COVERAGE_ID, 3, 4)", "CANDIDATE_IDS = (mon.COVERAGE_ID,)"),
("second start is allowed",
" if self.tool_id is not None:\n raise RuntimeError(\"linecov is already started\")\n", ""),
]
caught = 0
for name, old, new in MUTANTS:
if SOURCE.count(old) != 1:
print(f"SKIP {name}: pattern found {SOURCE.count(old)} times")
continue
work = tempfile.mkdtemp(prefix="mut_")
try:
with open(os.path.join(work, "linecov.py"), "w", encoding="utf-8", newline="\n") as handle:
handle.write(SOURCE.replace(old, new))
shutil.copytree(os.path.join(HERE, "tooltests"), os.path.join(work, "tooltests"))
done = subprocess.run(
[sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "tooltests"],
cwd=work, capture_output=True, text=True,
env={**os.environ, "PYTHONPATH": work, "COLUMNS": "170"},
)
match = re.search(r"(\d+) failed", done.stdout)
failed = int(match.group(1)) if match else 0
verdict = "caught" if done.returncode != 0 else "SURVIVED"
caught += done.returncode != 0
print(f"{verdict:<9} {name:<42} failing tests: {failed}")
finally:
shutil.rmtree(work, ignore_errors=True)
print(f"{caught} of {len(MUTANTS)} planted bugs caught")
python mutants.py
caught root without a trailing separator failing tests: 1
caught path case not normalized in _wanted failing tests: 8
caught line callback forgets DISABLE failing tests: 2
caught start callback forgets DISABLE failing tests: 2
caught stop leaves local events on failing tests: 1
caught stop never frees the tool id failing tests: 13
caught running frames are not watched failing tests: 1
caught switch_context forgets restart_events failing tests: 1
caught docstring lines stay in the denominator failing tests: 2
caught line zero stays in the denominator failing tests: 2
caught ranges merge a gap of two failing tests: 1
caught no fallback tool id failing tests: 1
caught second start is allowed failing tests: 3
13 of 13 planted bugs caught
Every planted bug is caught. The first version of this check was not so clean: it caught 11 of 13. One planted bug was a typo in my own pattern. The other was “stop leaves local events on”, which survived because my first test only looked at the stopped tool’s own counters, and stop() had already unregistered the callbacks, so nothing showed. The damage from that bug lands on the next tool that takes the ID, which is trap 1. I rewrote the test so that a second tool claims the ID and asserts that it receives no events. The numbers in the right-hand column are how many of the 19 tests fail for each planted bug. Six of the planted bugs fail exactly one test, one fails 13 because a leaked ID breaks every later test, and none fails zero. I ran the mutation check on Python 3.13.14 only. On 3.15.2 I would expect the “local events” bug to survive, because free_tool_id now clears local events by itself.
Common mistakes, in one place
- Assuming ID 1 is free. coverage.py’s
sysmoncore may own it. Claim an ID with a fallback and report who holds the others. - Filtering inside the callback and thinking that is the optimization. It cut the recorded data from 2,915 pairs to 28 and the callback count by nothing. Return
DISABLE, or never turn the event on for that code. - Comparing paths as plain strings. Use
os.path.normcaseand a trailing separator, orC:\Lab\Appwill not matchc:\lab\appandapp2will matchapp. - Forgetting
restart_events()between contexts. Every test after the first loses credit for lines that an earlier test ran. - Using
PY_STARTscoping without seeding running frames. The file that callsstart()silently disappears from the report. - Counting
co_lines()output as the denominator. Drop line 0 and docstring lines, then compare with coverage.py once. - Trusting a stop that only frees the ID. On 3.12 and 3.13 the next tool inherits your callbacks and local events.
Confirm that everything works end to end
From the covlab folder with the virtual environment active, these four commands should give the results shown. Timings will differ.
python -m pytest -q tooltests
python covrun.py --root app -m pytest -q
python crosscheck.py
python step_variant.py linecov_v4
You should see 19 passed; then 7 passed followed by a report with shop.py at 100%; then four collectors reporting 25 lines each with same as linecov: True and a final True; and finally a count of a few hundred callbacks with 28 shop.py lines. If the second command reports a tool-ID error, something else (probably coverage.py) holds IDs 1, 3 and 4.
Where to go next
- Branch coverage. A line can run while one side of its
ifnever does. The docs listBRANCH_LEFTandBRANCH_RIGHTevents and say that the olderBRANCHevent “is deprecated in 3.14”, because the two new events “can be disabled independently”. They arrive with that deprecation in Python 3.14, which is why this post stayed with lines and runs unchanged on 3.12 and 3.13. - A call tracer. Register
PY_STARTandPY_RETURNcallbacks, keep a stack of start times and you can build a simple deterministic profiler. For a sampling alternative, see the post on the Python 3.15 Tachyon profiler. - Watching what code does, not just where it runs. Another interpreter hook with a very different purpose is the audit hook, covered in How to Catch a Malicious Python Package at Import Time With Audit Hooks.
- Memory instead of lines. If the question is “what is eating my RAM”, read How to Find and Fix a Memory Leak in a Python Service With tracemalloc.
- For real projects, use coverage.py. You now know what its
sysmoncore does underneath, and where its documented limits come from.
Sources and further reading
- sys.monitoring: Execution event monitoring, Python documentation (read at the 3.15.2 version of the page).
- PEP 669: Low Impact Monitoring for CPython.
- coverage.py configuration reference, the
coreoption. - The Python data model, code objects and
co_lines().








No Comment! Be the first one.