---
title: Tracing API
description: Line-by-line Python execution tracing with hit counts and per-variable
  snapshots via `sys.monitoring`.
order: 1
---
Call `tracefunc(fn, *args, **kwargs)` to record each executed AST statement (including separate statements on one line and per-iteration comprehension values) along with its hit count and up to 10 sampled `(type_name, repr_str)` values per variable. Pass `target_func` to trace calls to a specific inner function along with their call stack from `fn`.

```python
def _demo(n):
    total = sum(i * i for i in range(n))
    return total

traces = tracefunc(_demo, 4)
assert traces.exc is None and traces[0][1]["return total"][0] == 1
```

If `fn` raises, [`tracefunc`](core.md#tracefunc) stores the exception on `res.exc` and returns all traces gathered before the failure. Raises `RuntimeError` on Python \< 3.12 and `ValueError` or `OSError` when source code for the target function cannot be read.

## TraceResults

```python
def TraceResults(
    *args, **kwargs
):
```

*Result of [`tracefunc`](core.md#tracefunc): a list of `(stack_str, trace_dict)` per-call tuples; `exc` holds the exception `fn` raised, if any.*

## tracefunc

```python
def tracefunc(
    fn, /, *args, target_func=None, # Function whose calls are recorded (defaults to `fn`)
    incl_unhit:bool=False, # Include lines with 0 hits in each trace dict?
    **kwargs
)->tracefunc.core.TraceResults: # Up to 10 `(stack_str, trace_dict)` entries, with `exc` set if `fn` raised
```

*Trace `fn(*args, **kwargs)` via `sys.monitoring`, returning a [`TraceResults`](core.md#traceresults) list of `(stack_str, trace_dict)` pairs.*
