Skip to content

Truncate long object representations in to_repr #3773

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

liblaf
Copy link

@liblaf liblaf commented Jun 19, 2025

Type of changes

  • Bug fix
  • New feature
  • Documentation / docstrings
  • Tests
  • Other

Checklist

  • I've run the latest black with default args on new code.
  • I've updated CHANGELOG.md and CONTRIBUTORS.md where appropriate.
  • I've added tests for new code.
  • I accept that @willmcgugan may be pedantic in the code review.

Description

Hi Rich maintainers,

First off, thank you for creating and maintaining rich – it's an incredibly useful library that I use frequently!

This PR addresses the issue of very long object representations in tracebacks, especially when show_locals=True is enabled. Objects like large NumPy arrays, PyTorch tensors, or JAX arrays can produce extremely verbose repr() outputs, making tracebacks difficult to read and navigate.

Currently, to_repr truncates strings and bytes if they exceed max_string. This change extends similar truncation logic to the generic repr(obj) output. If max_string is set and the repr() of an object exceeds this length, it will be truncated with an ellipsis (...).

This is a partial solution that helps improve readability for general objects whose repr() is too long. It doesn't allow for type-specific custom representations, which has been discussed in issues like #3393 and PR #3394. I believe allowing external registration of __rich_repr__ or similar custom display functions would be a more comprehensive solution, as mentioned in discussion #1258. See discussion #3774.

However, I hope this small change can provide an immediate improvement for users dealing with overly long representations in tracebacks.

Thank you for your consideration and for all your work on Rich!

@@ -610,6 +610,8 @@ def to_repr(obj: Any) -> str:
else:
try:
obj_repr = repr(obj)
if max_string is not None and len(obj_repr) > max_string:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not keen on using max_string for things other than repr. Suggest max_repr.

Additionally, these two lines don't belong within the Exception block, since we aren't expecting this code to throw exceptions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants