Skip to content

Commit 73dc2bf

Browse files
daiyippyglove authors
authored andcommitted
Add options to limit the length of str/bytes during formatting.
PiperOrigin-RevId: 657346887
1 parent e6810a8 commit 73dc2bf

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

pyglove/core/object_utils/formatting.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,8 @@ def format( # pylint: disable=redefined-builtin
124124
include_keys: Optional[Set[str]] = None,
125125
exclude_keys: Optional[Set[str]] = None,
126126
markdown: bool = False,
127+
max_str_len: int | None = None,
128+
max_bytes_len: int | None = None,
127129
**kwargs,
128130
) -> str:
129131
"""Formats a (maybe) hierarchical value with flags.
@@ -143,6 +145,10 @@ def format( # pylint: disable=redefined-builtin
143145
exclude_keys: A set of keys to exclude from the top-level dict or object.
144146
Applicable only when `include_keys` is set to None.
145147
markdown: If True, use markdown notion to quote the formatted object.
148+
max_str_len: The max length of the string to be formatted. If the string is
149+
longer than this length, it will be truncated.
150+
max_bytes_len: The max length of the bytes to be formatted. If the bytes is
151+
longer than this length, it will be truncated.
146152
**kwargs: Keyword arguments that will be passed through unto child
147153
``Formattable`` objects.
148154
@@ -210,6 +216,12 @@ def _format_child(v):
210216
s.append(_indent('}', root_indent))
211217
else:
212218
if isinstance(value, str):
219+
if max_str_len is not None and len(value) > max_str_len:
220+
value = value[:max_str_len] + '...'
221+
s = [repr(value)]
222+
elif isinstance(value, bytes):
223+
if max_bytes_len is not None and len(value) > max_bytes_len:
224+
value = value[:max_bytes_len] + b'...'
213225
s = [repr(value)]
214226
else:
215227
s = [repr(value) if compact else str(value)]

pyglove/core/object_utils/formatting_test.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,14 @@ def test_markdown(self):
218218
"""),
219219
)
220220

221+
def test_max_len(self):
222+
self.assertEqual(
223+
formatting.format('foo', max_str_len=2), '\'fo...\''
224+
)
225+
self.assertEqual(
226+
formatting.format(b'bar', max_bytes_len=2), 'b\'ba...\''
227+
)
228+
221229

222230
if __name__ == '__main__':
223231
unittest.main()

0 commit comments

Comments
 (0)