Claude Code for trace: Python Execution Tracer and Coverage — Claude Skills 360 Blog
Blog / AI / Claude Code for trace: Python Execution Tracer and Coverage
AI

Claude Code for trace: Python Execution Tracer and Coverage

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

Python’s trace module traces statement execution and records line-level coverage without any third-party dependencies. import trace. Create: t = trace.Trace(count=True, trace=False, countfuncs=False, countcallers=False, ignoremods=(), ignoredirs=())count=True counts executions per line; trace=True prints each line as it runs; countfuncs=True records whether each function was called; countcallers=True builds a caller → callee dict. Ignore: ignoremods=["unittest"] — exclude modules by name; ignoredirs=[sysconfig.get_path("stdlib")] — exclude directories by prefix. Run callable: t.runfunc(fn, *args, **kwargs) — traces fn and returns its result. Run code string: t.run("import os; os.getcwd()"). Results: r = t.results()CoverageResults object; r.countsdict[(filename, lineno), int]; r.write_results(show_missing=True, coverdir="/tmp/cover") — writes annotated .cover files. Command line: python -m trace --count -C cover_dir script.py — same functionality from the shell. Claude Code generates statement coverage collectors, execution tracers, function call graphs, and lightweight CI coverage reporters.

CLAUDE.md for trace

## trace Stack
- Stdlib: import trace, sys
- Create: t = trace.Trace(count=True, trace=False)
- Run:    result = t.runfunc(my_function, arg1, arg2)
- Results: r = t.results()    # CoverageResults
- Counts:  r.counts           # {(filename, lineno): exec_count}
- Write:   r.write_results(show_missing=True, coverdir="/tmp/cover")
- Ignore:  ignoredirs=[sysconfig.get_path("stdlib")]
- CLI:     python -m trace --count -C ./cover script.py

trace Execution Tracing Pipeline

# app/traceutil.py — coverage, tracer, call graph, reporter
from __future__ import annotations

import sys
import sysconfig
import trace
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable


# ─────────────────────────────────────────────────────────────────────────────
# 1. Helpers for ignoring stdlib / third-party
# ─────────────────────────────────────────────────────────────────────────────

def _stdlib_dirs() -> list[str]:
    """Return a list of stdlib directory prefixes to exclude."""
    dirs = []
    for key in ("stdlib", "platstdlib", "purelib", "platlib"):
        p = sysconfig.get_path(key)
        if p:
            dirs.append(p)
    return dirs


def make_tracer(
    count: bool = True,
    trace_lines: bool = False,
    countfuncs: bool = False,
    countcallers: bool = False,
    ignore_stdlib: bool = True,
    extra_ignoredirs: "list[str] | None" = None,
    ignoremods: "list[str] | None" = None,
) -> trace.Trace:
    """
    Create a configured Trace instance with sensible defaults.

    Example:
        t = make_tracer(count=True, ignore_stdlib=True)
        t.runfunc(my_function, x, y)
        report_coverage(t.results(), "src/")
    """
    ignoredirs = (_stdlib_dirs() if ignore_stdlib else []) + (extra_ignoredirs or [])
    return trace.Trace(
        count=count,
        trace=trace_lines,
        countfuncs=countfuncs,
        countcallers=countcallers,
        ignoredirs=ignoredirs,
        ignoremods=ignoremods or [],
    )


# ─────────────────────────────────────────────────────────────────────────────
# 2. Coverage collection
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class LineCount:
    """Execution count info for one source file."""
    filename:   str
    total_lines: int
    executed:   int
    missed:     int
    coverage_pct: float
    missed_lines: list[int] = field(default_factory=list)

    def __str__(self) -> str:
        return (
            f"{self.filename}  "
            f"{self.executed}/{self.total_lines} lines  "
            f"{self.coverage_pct:.1f}%"
            + (f"  missed={self.missed_lines}" if self.missed_lines else "")
        )


@dataclass
class CoverageReport:
    """Coverage report for one traced execution."""
    files:      list[LineCount] = field(default_factory=list)

    @property
    def total_lines(self) -> int:
        return sum(f.total_lines for f in self.files)

    @property
    def executed_lines(self) -> int:
        return sum(f.executed for f in self.files)

    @property
    def overall_pct(self) -> float:
        if self.total_lines == 0:
            return 0.0
        return 100.0 * self.executed_lines / self.total_lines

    def __str__(self) -> str:
        lines = [f"CoverageReport: {self.overall_pct:.1f}% "
                 f"({self.executed_lines}/{self.total_lines})"]
        for f in self.files:
            lines.append(f"  {f}")
        return "\n".join(lines)


def coverage_of_file(
    source_path: "str | Path",
    counts: "dict[tuple, int]",
) -> "LineCount | None":
    """
    Compute coverage stats for one source file given the counts dict.

    Example:
        t = make_tracer()
        t.runfunc(fn)
        lc = coverage_of_file("mymodule.py", t.results().counts)
    """
    p = Path(source_path).resolve()
    src_str = str(p)

    # Collect executed line numbers for this file
    executed = {lineno for (fname, lineno), cnt in counts.items()
                if Path(fname).resolve() == p and cnt > 0}

    if not p.exists():
        return None

    # Count executable lines (non-empty, non-comment)
    executable: list[int] = []
    for i, line in enumerate(p.read_text().splitlines(), 1):
        stripped = line.strip()
        if stripped and not stripped.startswith("#"):
            executable.append(i)

    if not executable:
        return None

    total = len(executable)
    exec_count = sum(1 for ln in executable if ln in executed)
    missed = [ln for ln in executable if ln not in executed]

    pct = 100.0 * exec_count / total if total else 0.0
    return LineCount(
        filename=str(p),
        total_lines=total,
        executed=exec_count,
        missed=total - exec_count,
        coverage_pct=pct,
        missed_lines=missed,
    )


def report_coverage(
    results: trace.CoverageResults,
    source_root: "str | Path",
) -> CoverageReport:
    """
    Build a CoverageReport for all .py files under source_root
    that appear in the trace results.

    Example:
        t = make_tracer()
        t.runfunc(run_app)
        report = report_coverage(t.results(), "src/myapp")
        print(report)
    """
    root = Path(source_root).resolve()
    counts = results.counts
    seen: set[Path] = set()
    for (fname, _) in counts.keys():
        p = Path(fname).resolve()
        if str(p).startswith(str(root)):
            seen.add(p)

    file_reports = []
    for p in sorted(seen):
        lc = coverage_of_file(p, counts)
        if lc:
            file_reports.append(lc)

    return CoverageReport(files=file_reports)


# ─────────────────────────────────────────────────────────────────────────────
# 3. Function coverage (countfuncs)
# ─────────────────────────────────────────────────────────────────────────────

def called_functions(
    fn: Callable,
    *args,
    ignore_stdlib: bool = True,
    **kwargs,
) -> dict[str, list[str]]:
    """
    Return a dict of {module: [function_names]} called during fn(*args).
    Uses countfuncs=True mode.

    Example:
        calls = called_functions(my_app.run, config)
        for mod, fns in calls.items():
            print(f"  {mod}: {fns}")
    """
    t = make_tracer(count=False, countfuncs=True, ignore_stdlib=ignore_stdlib)
    t.runfunc(fn, *args, **kwargs)
    r = t.results()
    result: dict[str, list[str]] = {}
    for (filename, modname, funcname) in r.calledfuncs:
        result.setdefault(modname or filename, []).append(funcname)
    return result


# ─────────────────────────────────────────────────────────────────────────────
# 4. Line-by-line tracer context manager
# ─────────────────────────────────────────────────────────────────────────────

class TraceContext:
    """
    Context manager that traces execution of a block and exposes the results.

    Example:
        with TraceContext(ignore_stdlib=True) as tc:
            result = my_computation(data)
        print(report_coverage(tc.results, "src/"))
    """

    def __init__(self, ignore_stdlib: bool = True, countfuncs: bool = False) -> None:
        self._tracer = make_tracer(
            count=True,
            ignore_stdlib=ignore_stdlib,
            countfuncs=countfuncs,
        )
        self.results: "trace.CoverageResults | None" = None

    def __enter__(self) -> "TraceContext":
        # Install sys.settrace manually so tracing applies to the with-block
        # Note: trace.Trace.runfunc is simpler; this gives block-level control
        self._old_trace = sys.gettrace()
        sys.settrace(self._tracer.localtrace)
        return self

    def __exit__(self, *_: object) -> None:
        sys.settrace(self._old_trace)
        self.results = self._tracer.results()


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    import tempfile

    print("=== trace demo ===")

    with tempfile.TemporaryDirectory() as td:
        td_path = Path(td)

        # ── write a module to trace ────────────────────────────────────────────
        subject = td_path / "subject.py"
        subject.write_text(
            "def add(a, b):\n"
            "    return a + b\n"
            "\n"
            "def subtract(a, b):\n"
            "    return a - b\n"
            "\n"
            "def run():\n"
            "    x = add(10, 5)\n"
            "    y = add(x, 3)\n"
            "    return y\n"
        )

        # Import the subject module
        import importlib.util
        spec = importlib.util.spec_from_file_location("subject", subject)
        subject_mod = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(subject_mod)

        # ── basic coverage trace ───────────────────────────────────────────────
        print("\n--- make_tracer + runfunc + coverage_of_file ---")
        t = make_tracer(count=True, ignore_stdlib=True)
        result_val = t.runfunc(subject_mod.run)
        print(f"  run() returned: {result_val}")

        lc = coverage_of_file(subject, t.results().counts)
        if lc:
            print(f"  {lc}")

        # ── report_coverage ───────────────────────────────────────────────────
        print("\n--- report_coverage ---")
        report = report_coverage(t.results(), td_path)
        print(report)

        # ── countfuncs ────────────────────────────────────────────────────────
        print("\n--- called_functions ---")
        calls = called_functions(subject_mod.run, ignore_stdlib=True)
        for mod, fns in sorted(calls.items()):
            print(f"  {mod}: {fns}")

        # ── write_results to disk ─────────────────────────────────────────────
        print("\n--- write_results ---")
        cover_dir = td_path / "cover"
        cover_dir.mkdir()
        t.results().write_results(show_missing=True, coverdir=str(cover_dir))
        cover_files = list(cover_dir.glob("*.cover"))
        print(f"  wrote {len(cover_files)} .cover file(s)")
        if cover_files:
            lines = cover_files[0].read_text().splitlines()
            for line in lines[:6]:
                print(f"    {line}")

        # ── trace_lines mode ──────────────────────────────────────────────────
        print("\n--- trace_lines mode ---")
        import io as _io
        old_stdout = sys.stdout
        sys.stdout = _io.StringIO()
        t2 = make_tracer(count=False, trace_lines=True, ignore_stdlib=True)
        t2.runfunc(subject_mod.add, 3, 4)
        output = sys.stdout.getvalue()
        sys.stdout = old_stdout
        for line in output.strip().splitlines()[:4]:
            print(f"  traced: {line}")

    print("\n=== done ===")

For the coverage.py (PyPI) alternative — coverage run and coverage report provide branch coverage, .coverage data files, HTML/XML/JSON reports, parallel mode, and plugin architecture — use coverage.py for all production coverage measurement; use trace (stdlib) when you cannot install third-party packages, need a quick one-off coverage check in a minimal environment, or want to programmatically inspect the counts dict directly. For the sys.settrace alternative — sys.settrace(handler) installs a low-level line/call/return/exception event hook at the interpreter level — use sys.settrace when you need full control over the profiling callback (e.g., to log specific variable values or instrument individual functions); use trace.Trace when you just want execution counts or a call graph without writing the event dispatcher yourself. The Claude Skills 360 bundle includes trace skill sets covering make_tracer() with ignore_stdlib/countfuncs/countcallers options, LineCount/CoverageReport dataclasses, coverage_of_file() per-file coverage stats, report_coverage() multi-file coverage reporter, called_functions() countfuncs driver, and TraceContext context manager with results attribute. Start with the free tier to try execution tracing patterns and trace 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