Skip to content

Commit

Permalink
Merge pull request #3472 from Textualize/fix-bad-dataclass
Browse files Browse the repository at this point in the history
fix for missing field in dataclass
  • Loading branch information
willmcgugan authored Aug 26, 2024
2 parents b6f2f7a + c938830 commit dc7a195
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Fixed superfluous space above Markdown tables https://github.com/Textualize/rich/pull/3469
- Fixed issue with record and capture interaction https://github.com/Textualize/rich/pull/3470
- Fixed control codes breaking in `append_tokens` https://github.com/Textualize/rich/pull/3471
- Fixed exception pretty printing a dataclass with missing fields https://github.com/Textualize/rich/pull/3472

### Changed

Expand Down
4 changes: 3 additions & 1 deletion rich/pretty.py
Original file line number Diff line number Diff line change
Expand Up @@ -781,7 +781,9 @@ def iter_attrs() -> (
)

for last, field in loop_last(
field for field in fields(obj) if field.repr
field
for field in fields(obj)
if field.repr and hasattr(obj, field.name)
):
child_node = _traverse(getattr(obj, field.name), depth=depth + 1)
child_node.key_repr = field.name
Expand Down
20 changes: 20 additions & 0 deletions tests/test_pretty.py
Original file line number Diff line number Diff line change
Expand Up @@ -734,3 +734,23 @@ def __rich_repr__(self):
yield None, (1,), (1,)

assert pretty_repr(Foo()) == "Foo()"


def test_dataclass_no_attribute() -> None:
"""Regression test for https://github.com/Textualize/rich/issues/3417"""
from dataclasses import dataclass, field

@dataclass(eq=False)
class BadDataclass:
item: int = field(init=False)

# item is not provided
bad_data_class = BadDataclass()

console = Console()
with console.capture() as capture:
console.print(bad_data_class)

expected = "BadDataclass()\n"
result = capture.get()
assert result == expected

0 comments on commit dc7a195

Please sign in to comment.