Skip to content
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

fix for missing field in dataclass #3472

Merged
merged 2 commits into from
Aug 26, 2024
Merged
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
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
Loading