Skip to content

Commit 8c0619d

Browse files
committed
perf: defer Traceback import in logging.py to reduce RichHandler import 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.
1 parent fc41075 commit 8c0619d

3 files changed

Lines changed: 14 additions & 3 deletions

File tree

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## [Unreleased]
9+
10+
### Changed
11+
12+
- Defer import of Traceback in logging.py to reduce RichHandler import time by ~20ms
13+
814
## [14.3.3] - 2026-02-19
915

1016
### Fixed

CONTRIBUTORS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,3 +100,4 @@ The following people have contributed to the development of Rich:
100100
- [Brandon Capener](https://github.com/bcapener)
101101
- [Alex Zheng](https://github.com/alexzheng111)
102102
- [Sebastian Speitel](https://github.com/SebastianSpeitel)
103+
- [Kevin Turcios](https://github.com/KRRT7)

rich/logging.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@
33
from logging import Handler, LogRecord
44
from pathlib import Path
55
from types import ModuleType
6-
from typing import ClassVar, Iterable, List, Optional, Type, Union
6+
from typing import TYPE_CHECKING, ClassVar, Iterable, List, Optional, Type, Union
7+
8+
if TYPE_CHECKING:
9+
from .traceback import Traceback
710

811
from rich._null_file import NullFile
912

@@ -12,7 +15,6 @@
1215
from .console import Console, ConsoleRenderable
1316
from .highlighter import Highlighter, ReprHighlighter
1417
from .text import Text
15-
from .traceback import Traceback
1618

1719

1820
class RichHandler(Handler):
@@ -141,6 +143,8 @@ def emit(self, record: LogRecord) -> None:
141143
exc_type, exc_value, exc_traceback = record.exc_info
142144
assert exc_type is not None
143145
assert exc_value is not None
146+
from .traceback import Traceback
147+
144148
traceback = Traceback.from_exception(
145149
exc_type,
146150
exc_value,
@@ -208,7 +212,7 @@ def render(
208212
self,
209213
*,
210214
record: LogRecord,
211-
traceback: Optional[Traceback],
215+
traceback: Optional["Traceback"],
212216
message_renderable: "ConsoleRenderable",
213217
) -> "ConsoleRenderable":
214218
"""Render log for display.

0 commit comments

Comments
 (0)