From 6055e2d8ef98e5487949b9c6e5d0dfce6a5b9e28 Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Mon, 26 Aug 2024 16:59:16 +0100 Subject: [PATCH] fix for missing field in dataclass --- rich/pretty.py | 4 +++- tests/test_pretty.py | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/rich/pretty.py b/rich/pretty.py index e0c78f627..5c725c0c5 100644 --- a/rich/pretty.py +++ b/rich/pretty.py @@ -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 diff --git a/tests/test_pretty.py b/tests/test_pretty.py index 929de1cff..7ab4f8e79 100644 --- a/tests/test_pretty.py +++ b/tests/test_pretty.py @@ -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