Python’s bdb module provides the base debugger infrastructure — the Bdb class handles sys.settrace dispatch and breakpoint management, giving you hooks to intercept every function call, line execution, return, and exception in a running Python program. import bdb. Override hooks: user_call(frame, argument_list), user_line(frame), user_return(frame, return_value), user_exception(frame, exc_info). Control flow: set_step() — stop on next line; set_next(frame) — step over; set_return(frame) — run to return; set_continue() — resume; set_quit() — stop everything. Breakpoints: set_break(filename, lineno, temporary=False, cond=None, funcname=None) → str|None (error or None); clear_break(filename, lineno); Bdb.get_breaks(filename, lineno) → list; bdb.Breakpoint(file, line, temporary, cond, funcname) — the Breakpoint class. Install: self.set_trace() installs sys.settrace(self.trace_dispatch) from the callers frame. pdb.Pdb inherits from bdb.Bdb. Claude Code generates execution recorders, call tracers, coverage instrumentation hooks, and custom interactive debuggers.
CLAUDE.md for bdb
## bdb Stack
- Stdlib: import bdb, sys
- Subclass: class MyDbg(bdb.Bdb):
- def user_line(self, frame): ... # per line
- def user_call(self, frame, arg): ...
- def user_return(self, frame, rv): ...
- Install: dbg = MyDbg(); dbg.run("fn()") # OR
- dbg.set_trace() # from current frame
- Break: dbg.set_break("script.py", 10)
- Control: dbg.set_step() / set_continue() / set_quit()
- Note: pdb.Pdb inherits from bdb.Bdb
bdb Debugger Base Pipeline
# app/bdbutil.py — recorder, call tracer, breakpoint sentinel, coverage hook
from __future__ import annotations
import bdb
import sys
import linecache
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable
# ─────────────────────────────────────────────────────────────────────────────
# 1. Execution recorder
# ─────────────────────────────────────────────────────────────────────────────
@dataclass
class ExecutionEvent:
"""One recorded debug event."""
kind: str # "call", "line", "return", "exception"
filename: str
lineno: int
funcname: str
source: str # source text for the line (may be empty)
value: Any = None # return value or exc_info
class ExecutionRecorder(bdb.Bdb):
"""
Record every line execution (and optionally calls/returns) in a function.
Example:
recorder = ExecutionRecorder(record_calls=True)
recorder.runcall(my_function, arg1, arg2)
for evt in recorder.events:
print(evt.kind, evt.filename, evt.lineno, evt.source[:40])
"""
def __init__(
self,
record_calls: bool = False,
record_returns: bool = False,
ignore_stdlib: bool = True,
) -> None:
super().__init__()
self.events: list[ExecutionEvent] = []
self.record_calls = record_calls
self.record_returns = record_returns
self.ignore_stdlib = ignore_stdlib
self._stdlib_prefix = str(Path(sys.prefix))
def _should_skip(self, filename: str) -> bool:
if not filename:
return True
if self.ignore_stdlib and filename.startswith(self._stdlib_prefix):
return True
return False
def _source_line(self, filename: str, lineno: int) -> str:
line = linecache.getline(filename, lineno)
return line.rstrip()
def user_line(self, frame) -> None:
filename = frame.f_code.co_filename
if self._should_skip(filename):
return
lineno = frame.f_lineno
self.events.append(ExecutionEvent(
kind="line",
filename=filename,
lineno=lineno,
funcname=frame.f_code.co_name,
source=self._source_line(filename, lineno),
))
def user_call(self, frame, argument_list) -> None:
if not self.record_calls:
return
filename = frame.f_code.co_filename
if self._should_skip(filename):
return
self.events.append(ExecutionEvent(
kind="call",
filename=filename,
lineno=frame.f_lineno,
funcname=frame.f_code.co_name,
source="",
))
def user_return(self, frame, return_value) -> None:
if not self.record_returns:
return
filename = frame.f_code.co_filename
if self._should_skip(filename):
return
self.events.append(ExecutionEvent(
kind="return",
filename=filename,
lineno=frame.f_lineno,
funcname=frame.f_code.co_name,
source="",
value=return_value,
))
def user_exception(self, frame, exc_info) -> None:
filename = frame.f_code.co_filename
if self._should_skip(filename):
return
self.events.append(ExecutionEvent(
kind="exception",
filename=filename,
lineno=frame.f_lineno,
funcname=frame.f_code.co_name,
source=self._source_line(filename, frame.f_lineno),
value=exc_info,
))
# ─────────────────────────────────────────────────────────────────────────────
# 2. Call counter / function tracer
# ─────────────────────────────────────────────────────────────────────────────
class CallCounter(bdb.Bdb):
"""
Count how many times each function is called during execution.
Example:
counter = CallCounter()
counter.runcall(main)
for (fn, file), count in counter.call_counts.items():
print(f" {fn} ({file}): {count}")
"""
def __init__(self) -> None:
super().__init__()
self.call_counts: dict[tuple[str, str], int] = {}
def user_call(self, frame, argument_list) -> None:
key = (frame.f_code.co_name, frame.f_code.co_filename)
self.call_counts[key] = self.call_counts.get(key, 0) + 1
def top_callers(self, n: int = 10) -> list[tuple[str, str, int]]:
"""Return top-N (funcname, filename, count) sorted by count."""
return sorted(
[(fn, fname, cnt) for (fn, fname), cnt in self.call_counts.items()],
key=lambda x: -x[2],
)[:n]
# ─────────────────────────────────────────────────────────────────────────────
# 3. Conditional breakpoint trap
# ─────────────────────────────────────────────────────────────────────────────
class BreakpointTrap(bdb.Bdb):
"""
Run a function until a specific file:lineno is hit, then invoke a callback.
Continues execution after the callback returns.
Example:
def on_hit(frame):
print(f" HIT: locals={frame.f_locals}")
trap = BreakpointTrap("script.py", 15, callback=on_hit)
trap.runcall(run_script)
"""
def __init__(
self,
filename: str,
lineno: int,
callback: "Callable | None" = None,
hit_limit: int = 0,
) -> None:
super().__init__()
self._target_file = str(Path(filename).resolve())
self._target_line = lineno
self._callback = callback
self._hit_limit = hit_limit
self.hit_count = 0
def user_line(self, frame) -> None:
fname = str(Path(frame.f_code.co_filename).resolve())
if fname == self._target_file and frame.f_lineno == self._target_line:
self.hit_count += 1
if self._callback:
self._callback(frame)
if self._hit_limit and self.hit_count >= self._hit_limit:
self.set_quit()
else:
self.set_continue()
# ─────────────────────────────────────────────────────────────────────────────
# 4. Coverage tracker (line set)
# ─────────────────────────────────────────────────────────────────────────────
class CoverageTracker(bdb.Bdb):
"""
Track which (filename, lineno) pairs were executed.
Lightweight alternative to the trace module for quick coverage checks.
Example:
cov = CoverageTracker()
cov.runcall(my_function, data)
executed = cov.executed_lines("src/mymodule.py")
print(f"executed {len(executed)} lines")
"""
def __init__(self, ignore_stdlib: bool = True) -> None:
super().__init__()
self.executed: set[tuple[str, int]] = set()
self._stdlib_prefix = str(Path(sys.prefix))
self.ignore_stdlib = ignore_stdlib
def user_line(self, frame) -> None:
fname = frame.f_code.co_filename
if self.ignore_stdlib and fname.startswith(self._stdlib_prefix):
return
self.executed.add((fname, frame.f_lineno))
def executed_lines(self, source_path: "str | Path") -> set[int]:
"""Return the set of executed line numbers for the given source file."""
target = str(Path(source_path).resolve())
return {ln for (fn, ln) in self.executed if Path(fn).resolve() == Path(target)}
# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
import tempfile
print("=== bdb demo ===")
def fib(n: int) -> int:
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
def compute():
total = 0
for i in range(5):
total += fib(i)
return total
# ── ExecutionRecorder ──────────────────────────────────────────────────────
print("\n--- ExecutionRecorder ---")
recorder = ExecutionRecorder(record_calls=True, record_returns=True, ignore_stdlib=True)
result = recorder.runcall(compute)
print(f" compute() = {result}")
lines_only = [e for e in recorder.events if e.kind == "line"]
calls_only = [e for e in recorder.events if e.kind == "call"]
returns_only = [e for e in recorder.events if e.kind == "return"]
print(f" events: {len(recorder.events)} total {len(lines_only)} lines "
f"{len(calls_only)} calls {len(returns_only)} returns")
print(" first 5 line events:")
for evt in lines_only[:5]:
src = evt.source.strip()[:50]
print(f" line {evt.lineno} {evt.funcname}: {src!r}")
# ── CallCounter ───────────────────────────────────────────────────────────
print("\n--- CallCounter ---")
counter = CallCounter()
counter.runcall(compute)
print(" top callers:")
for fn, fname, cnt in counter.top_callers(n=3):
print(f" {fn}: {cnt} calls")
# ── CoverageTracker ───────────────────────────────────────────────────────
print("\n--- CoverageTracker ---")
cov = CoverageTracker(ignore_stdlib=True)
cov.runcall(compute)
print(f" executed {len(cov.executed)} unique (file, line) pairs")
# Filter to __main__
main_lines = cov.executed_lines(__file__)
print(f" executed {len(main_lines)} lines in this file")
print("\n=== done ===")
For the sys.settrace built-in alternative — sys.settrace(handler) installs a raw trace function that receives (frame, event, arg) for every call/line/return/exception — use sys.settrace directly when you need minimal overhead and full control over the dispatch logic; use bdb.Bdb when you want the breakpoint management, set_step/set_next/set_continue state machine, and runcall/run/runctx entry points to be handled for you. For the trace module alternative — trace.Trace(count=True) counts line executions using the same sys.settrace mechanism but provides a higher-level results() / write_results() API — use trace when you want a coverage report; use bdb.Bdb when you need breakpoint logic, frame inspection callbacks, or the foundation for an interactive debugger. The Claude Skills 360 bundle includes bdb skill sets covering ExecutionEvent dataclass and ExecutionRecorder with user_line/user_call/user_return/user_exception hooks, CallCounter with top_callers(), BreakpointTrap with per-hit callback and hit_limit, and CoverageTracker with executed_lines(). Start with the free tier to try debugger tracing patterns and bdb pipeline code generation.