On this page
trace
Prev: tomllib | Up: stdlib_module | Next: traceback
Rel: typing, annotationlib, pydoc, pydoc_data, doctest
Ref: docs.python.org — trace
Tags: #public #python3 #stdlib
Import
import trace
Overview
Line-by-line execution tracer, statement coverage counter, and call-graph recorder (Trace, or python3 -m trace --trace/--count script.py). Use trace for zero-dependency quick debugging or basic line-count checks; for real test coverage reports (branches, HTML, CI thresholds), use coverage.py.
Quick Start
import trace
def compute(n: int) -> int:
total = 0
for i in range(n):
total += i
return total
tracer = trace.Trace(count=True, trace=False)
result = tracer.runfunc(compute, 5)
counts = tracer.results().counts
assert result == 10 and len(counts) > 0
Implementation Walkthrough
1. CLI Modes (python3 -m trace)
python3 -m trace --trace script.py— print every executed line as it runs.python3 -m trace --count -C coverdir script.py— write.coverfiles showing per-line execution counts.python3 -m trace --listfuncs script.py— list every function called during a run.
Gotchas & Boundaries
- Heavy runtime overhead: Tracing every Python line via
sys.settrace()slows execution substantially—use it for targeted debugging, not production. - No branch coverage:
traceonly counts executed lines; usecoverage.pyfor branch coverage and pytest integration.
Classes & Objects
- trace.CoverageResults —
trace.CoverageResultsclass. (Methods:.is_ignored_filename(),.update(),.write_results(),.write_results_file()) - trace.Trace —
trace.Traceclass. (Methods:.file_module_function_of(),.globaltrace_countfuncs(),.globaltrace_lt(),.globaltrace_trackcallers(),.localtrace_count(),.localtrace_trace())
Linked from
Related notes
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tomllib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/traceback Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/annotationlib Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/doctest Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/pydoc Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/pydoc_data Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/trace/CoverageResults Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/trace/Trace Linked here; shared tags: #stdlib