Skip to content

Commit

Permalink
fix for missing field in dataclass
Browse files Browse the repository at this point in the history
  • Loading branch information
willmcgugan committed Aug 26, 2024
1 parent b6f2f7a commit 6055e2d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
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 6055e2d

Please sign in to comment.