Claude Code for bdb: Python Debugger Base Infrastructure — Claude Skills 360 Blog
Blog / AI / Claude Code for bdb: Python Debugger Base Infrastructure
AI

Claude Code for bdb: Python Debugger Base Infrastructure

Published: December 24, 2028
Read time: 5 min read
By: Claude Skills 360

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.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free