Skip to content

perf: defer Traceback import in logging.py#1

Closed
KRRT7 wants to merge 3 commits intomasterfrom
perf/lazy-traceback-import
Closed

perf: defer Traceback import in logging.py#1
KRRT7 wants to merge 3 commits intomasterfrom
perf/lazy-traceback-import

Conversation

@KRRT7
Copy link
Copy Markdown
Owner

@KRRT7 KRRT7 commented Apr 9, 2026

Summary

  • Defer from .traceback import Traceback from module-level to inside emit(), only when rich_tracebacks is enabled
  • Avoids loading the traceback → syntax → pygments chain (~20ms) for the default RichHandler usage

Benchmarks (Standard_D2s_v5, Python 3.13, hyperfine)

Module Before After Delta
RichHandler 90.8 ms 82.4 ms -8.4 ms
Console → RichHandler gap 22.4 ms 3.0 ms -19.4 ms

The gap between Console and RichHandler (which isolates the Traceback import cost) collapsed from ~22ms to ~3ms.

Reproduce locally

# Quick single-branch test:
pip install -e .
python benchmarks/bench_import.py

# Compare branches with hyperfine (recommended):
python benchmarks/bench_import.py --compare master perf/lazy-traceback-import

The --compare flag uses hyperfine's native --parameter-list to measure both branches in a single invocation, producing a statistically rigorous relative comparison:

# What it runs under the hood:
hyperfine \
  -L branch master,perf/lazy-traceback-import \
  --setup 'git checkout {branch} && python -m pip install -e . -q' \
  -n '{branch}' \
  'python -c "from rich.logging import RichHandler"'

Checks

  • black --check passes
  • mypy -p rich --no-incremental passes (0 issues)
  • pytest tests/ passes (952 passed, 25 skipped)
  • CHANGELOG.md updated
  • CONTRIBUTORS.md updated

KRRT7 added 3 commits April 8, 2026 23:05
…rt time

Move the module-level `from .traceback import Traceback` to a lazy
import inside `emit()`, guarded by the `rich_tracebacks` check. This
avoids loading the traceback -> syntax -> pygments chain (~20ms) when
RichHandler is used without rich tracebacks enabled (the default).

The Traceback type annotation in `render()` is changed to a string
literal for forward-reference compatibility.
Run `python benchmarks/bench_import.py` to measure RichHandler import
time and see the Console-to-RichHandler gap that this PR reduces.
Replace two separate hyperfine invocations with a single parameterized
run using -L branch. This produces a proper relative comparison with
statistical significance in one invocation.

Also adds a Console baseline measurement to show the optimization
only affects the traceback import chain, not the common path.
@KRRT7
Copy link
Copy Markdown
Owner Author

KRRT7 commented Apr 9, 2026

Superseded by the consolidated stacked PRs #12 + #13.

@KRRT7 KRRT7 closed this Apr 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant