How Do Debuggers See Every Line? Python's sys.settrace

This article explains how Python's sys.settrace reports calls, lines, returns and exceptions to a trace function, builds a small coverage tool with it, measures its overhead, and compares it with sys.monitoring.

A close view of the coils of a green tree python, row after row of small scales with scattered white flecks.
Photo by Richard Ortega on Unsplash

Debuggers that stop at a breakpoint and coverage tools that report which lines a test suite executed both need to observe a program while it runs, line by line, without modifying its source. The present article addresses sys.settrace, the CPython hook that calls a Python function for each call, line, return and exception of the running code. It describes the events and the rule that connects global and local trace functions, builds a small coverage tool, measures the slowdown that tracing causes, and situates the hook next to sys.monitoring, the lower-cost interface that Python 3.12 introduced and that Python 3.14 tools increasingly prefer. Seeing every step of a running program from inside the same interpreter is the secret weapon of sys.settrace.

Trace Events and Local Trace Functions

A trace function receives three arguments: the current frame, the name of the event and an argument whose meaning depends on the event, such as the value returned for "return" or the exception information for "exception". The function registered with sys.settrace is the global one and is called only for "call" events; whatever it returns becomes the local trace function of that frame and receives its line, return and exception events, so returning None leaves a function untraced. The following example records the events of a short loop, with line numbers relative to the def statement.

import sys


def work(n):
    total = 0
    for i in range(n):
        total += i
    return total


events = []


def tracer(frame, event, arg):
    if frame.f_code.co_name != "work":
        return None
    line = frame.f_lineno - frame.f_code.co_firstlineno
    events.append(f"{event}:{line}")
    if event == "return":
        events.append(f"value={arg}")
    return tracer


sys.settrace(tracer)
work(2)
sys.settrace(None)
print(" ".join(events))
# Output: call:0 line:1 line:2 line:3 line:2 line:3 line:2 line:4 return:4 value=1

The loop header appears three times because it is evaluated once per iteration and once more to detect the end, and the "return" event carries the value 1. There is no event for a change of variable: a tool that reports changes compares frame.f_locals between line events, the same frame objects examined in the article devoted to the inspect module. Line events follow the line table of the compiled code, which is why they map to the bytecode described in the article devoted to dis rather than to the visual layout of the source.

Building a Coverage Tool

Massively multiplayer games write every hit, heal and effect of a fight to a combat log, and separate add-ons read that log to build damage meters and fight reports without touching the game itself. This means that the interpreter, through sys.settrace, emits an event for every step of the program, and independent tools such as debuggers, coverage reporters and tracers turn that stream into their own views. The analogy, however, stops at this point, because the game writes its log regardless of whether anyone reads it, whereas a trace function is ordinary Python code that runs for every line and therefore slows the program down. The following example uses the stream to report the lines of a function that a test never executed.

import sys
from contextlib import contextmanager


def classify(n):
    if n < 0:
        return "negative"
    if n == 0:
        return "zero"
    return "positive"


@contextmanager
def line_coverage(func, hits):
    code = func.__code__

    def local(frame, event, arg):
        if event == "line":
            hits.add(frame.f_lineno - code.co_firstlineno)
        return local

    def global_(frame, event, arg):
        return local if frame.f_code is code else None

    previous = sys.gettrace()
    sys.settrace(global_)
    try:
        yield
    finally:
        sys.settrace(previous)


hits = set()
with line_coverage(classify, hits):
    classify(5)
    classify(-1)
body = set(range(1, 6))
print(sorted(body - hits))  # Output: [4]

The two calls covered the negative and positive branches, so the report identifies line 4, the return "zero" statement, as never executed. The global function returns a local tracer only for the code object of classify, which keeps every other call untraced, and the context manager restores whatever trace function was active before, so that the tool does not silently disable a debugger.

Pitfalls of sys.settrace

The hook runs arbitrary Python code inside the interpreter loop, so its pitfalls concern cost, scope and the coexistence of several tools. Six pitfalls are distinguished, which are the following:

  1. Large overhead. A tracer that handles every line makes loops several times slower, even when it does almost nothing.
  2. One thread only. sys.settrace affects the current thread; new threads need threading.settrace, and running threads need threading.settrace_all_threads, added in Python 3.12.
  3. One tracer at a time. A second call replaces the first, so a coverage tool and a debugger interfere unless each saves and restores sys.gettrace().
  4. Errors disable tracing. An exception raised inside the trace function propagates into the traced code and removes the trace function.
  5. Forgotten return values. A global function that returns None receives no line events for that frame, and a local one that returns None stops tracing the rest of it.
  6. Implementation detail. The documentation marks the hook as specific to CPython, and since Python 3.12 the lower-cost sys.monitoring is the recommended basis for new tools.

The first two pitfalls, and the alternative, are reproduced in the following example.

import sys
import threading
import time


def work(n):
    total = 0
    for i in range(n):
        total += i
    return total


def every_line(frame, event, arg):
    return every_line


def timed(tracer):
    sys.settrace(tracer)
    start = time.perf_counter()
    work(1_000_000)
    elapsed = time.perf_counter() - start
    sys.settrace(None)
    return elapsed


plain, traced = timed(None), timed(every_line)
print(traced > 3 * plain)  # Output: True

seen = []
sys.settrace(lambda frame, event, arg: seen.append(frame.f_code.co_name))
worker = threading.Thread(target=work, args=(3,))
worker.start()
worker.join()
sys.settrace(None)
print("work" in seen)  # Output: False

monitoring = sys.monitoring
TOOL = monitoring.COVERAGE_ID
lines = set()


def on_line(code, line):
    lines.add(line)
    return monitoring.DISABLE


monitoring.use_tool_id(TOOL, "demo")
monitoring.register_callback(TOOL, monitoring.events.LINE, on_line)
monitoring.set_events(TOOL, monitoring.events.LINE)
start = time.perf_counter()
work(1_000_000)
monitored = time.perf_counter() - start
monitoring.set_events(TOOL, 0)
monitoring.free_tool_id(TOOL)
print(monitored < 2 * plain)  # Output: True

On CPython 3.12, the loop took about 0.024 seconds untraced and 0.123 seconds with a tracer that only returns itself, roughly five times slower, while the thread started after sys.settrace produced no events at all. With sys.monitoring, the callback returns DISABLE after the first report of each line, so a coverage tool pays once per line instead of once per execution and the loop ran at its normal speed. For this reason, coverage.py uses sys.monitoring by default on Python 3.14, and in that version breakpoint() and the pdb command line also use the monitoring backend, while pdb.Pdb objects keep sys.settrace unless another backend is requested.

Choosing an Execution Hook

Consequently, sys.settrace remains the simplest way to observe execution in a few lines of Python, whereas tools meant to run on large programs should build on sys.monitoring, as the following table summarizes.

Situation Recommended approach
A quick experiment or a teaching tracer sys.settrace with a local trace function
Line coverage or debugging on Python 3.12 or later sys.monitoring, or tools built on it
Tracing threads threading.settrace or threading.settrace_all_threads
Where a program spends its time cProfile or a sampling profiler
Inspecting the call stack at one moment inspect.stack or sys._getframe
Running alongside other tools Saving and restoring sys.gettrace()

The measurement of time, as opposed to the observation of each step, is the subject of the profiling tutorial.

Conclusion

It is concluded that sys.settrace calls a global trace function for every new frame and a local one for its lines, returns and exceptions, which is enough to build tracers and coverage tools in a few lines of Python. This magic is expensive and fragile: it slows traced code several times, covers one thread, admits a single tool at a time and is removed by its own exceptions, which is why Python 3.12 added sys.monitoring and Python 3.14 tools adopted it. Separating business logic from the details of data storage, so that the same rules can work with a database or an in-memory list, is the purpose of the Repository pattern, which is developed in a future article of this series.