Skip to content

Commit dc7a195

Browse files
authored
Merge pull request #3472 from Textualize/fix-bad-dataclass
fix for missing field in dataclass
2 parents b6f2f7a + c938830 commit dc7a195

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
2323
- Fixed superfluous space above Markdown tables https://github.com/Textualize/rich/pull/3469
2424
- Fixed issue with record and capture interaction https://github.com/Textualize/rich/pull/3470
2525
- Fixed control codes breaking in `append_tokens` https://github.com/Textualize/rich/pull/3471
26+
- Fixed exception pretty printing a dataclass with missing fields https://github.com/Textualize/rich/pull/3472
2627

2728
### Changed
2829

rich/pretty.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -781,7 +781,9 @@ def iter_attrs() -> (
781781
)
782782

783783
for last, field in loop_last(
784-
field for field in fields(obj) if field.repr
784+
field
785+
for field in fields(obj)
786+
if field.repr and hasattr(obj, field.name)
785787
):
786788
child_node = _traverse(getattr(obj, field.name), depth=depth + 1)
787789
child_node.key_repr = field.name

tests/test_pretty.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -734,3 +734,23 @@ def __rich_repr__(self):
734734
yield None, (1,), (1,)
735735

736736
assert pretty_repr(Foo()) == "Foo()"
737+
738+
739+
def test_dataclass_no_attribute() -> None:
740+
"""Regression test for https://github.com/Textualize/rich/issues/3417"""
741+
from dataclasses import dataclass, field
742+
743+
@dataclass(eq=False)
744+
class BadDataclass:
745+
item: int = field(init=False)
746+
747+
# item is not provided
748+
bad_data_class = BadDataclass()
749+
750+
console = Console()
751+
with console.capture() as capture:
752+
console.print(bad_data_class)
753+
754+
expected = "BadDataclass()\n"
755+
result = capture.get()
756+
assert result == expected

0 commit comments

Comments
 (0)