Skip to content

Notes #3676

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Mar 28, 2025
Merged

Notes #3676

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## Unreleased

### Added

- Rich tracebacks will now render notes on Python 3.11 onwards (added with `Exception.add_note`) https://github.com/Textualize/rich/pull/3676

## [13.9.4] - 2024-11-01

Expand Down
1 change: 1 addition & 0 deletions rich/default_styles.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@
"traceback.exc_value": Style.null(),
"traceback.offset": Style(color="bright_red", bold=True),
"traceback.error_range": Style(underline=True, bold=True, dim=False),
"traceback.note": Style(color="green", bold=True),
"bar.back": Style(color="grey23"),
"bar.complete": Style(color="rgb(249,38,114)"),
"bar.finished": Style(color="rgb(114,156,31)"),
Expand Down
12 changes: 11 additions & 1 deletion rich/traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ class _SyntaxError:
line: str
lineno: int
msg: str
notes: List[str] = field(default_factory=list)


@dataclass
Expand All @@ -200,6 +201,7 @@ class Stack:
syntax_error: Optional[_SyntaxError] = None
is_cause: bool = False
frames: List[Frame] = field(default_factory=list)
notes: List[str] = field(default_factory=list)


@dataclass
Expand Down Expand Up @@ -403,6 +405,8 @@ def extract(

from rich import _IMPORT_CWD

notes: List[str] = getattr(exc_value, "__notes__", None) or []

def safe_str(_object: Any) -> str:
"""Don't allow exceptions from __str__ to propagate."""
try:
Expand All @@ -415,6 +419,7 @@ def safe_str(_object: Any) -> str:
exc_type=safe_str(exc_type.__name__),
exc_value=safe_str(exc_value),
is_cause=is_cause,
notes=notes,
)

if isinstance(exc_value, SyntaxError):
Expand All @@ -424,13 +429,14 @@ def safe_str(_object: Any) -> str:
lineno=exc_value.lineno or 0,
line=exc_value.text or "",
msg=exc_value.msg,
notes=notes,
)

stacks.append(stack)
append = stack.frames.append

def get_locals(
iter_locals: Iterable[Tuple[str, object]]
iter_locals: Iterable[Tuple[str, object]],
) -> Iterable[Tuple[str, object]]:
"""Extract locals from an iterator of key pairs."""
if not (locals_hide_dunder or locals_hide_sunder):
Expand Down Expand Up @@ -569,6 +575,7 @@ def __rich_console__(
stack_renderable = Constrain(stack_renderable, self.width)
with console.use_theme(traceback_theme):
yield stack_renderable

if stack.syntax_error is not None:
with console.use_theme(traceback_theme):
yield Constrain(
Expand All @@ -594,6 +601,9 @@ def __rich_console__(
else:
yield Text.assemble((f"{stack.exc_type}", "traceback.exc_type"))

for note in stack.notes:
yield Text.assemble(("[NOTE] ", "traceback.note"), highlighter(note))

if not last:
if stack.is_cause:
yield Text.from_markup(
Expand Down
15 changes: 15 additions & 0 deletions tests/test_traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -358,3 +358,18 @@ def test_traceback_finely_grained() -> None:
start, end = last_instruction
print(start, end)
assert start[0] == end[0]


@pytest.mark.skipif(
sys.version_info.minor < 11, reason="Not supported before Python 3.11"
)
def test_notes() -> None:
"""Check traceback captures __note__."""
try:
1 / 0
except Exception as error:
error.add_note("Hello")
error.add_note("World")
traceback = Traceback()

assert traceback.trace.stacks[0].notes == ["Hello", "World"]
Loading