diff --git a/CHANGES.rst b/CHANGES.rst index 5f55a8926..70840bb68 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -42,6 +42,10 @@ The ASDF Standard is at v1.6.0 from working. If you want these warnings to produce errors you can now add your own warning filter [#1757] + +- Only show ``str`` representation during ``info`` and ``search`` + if it contains a single line (and does not fail) [#1748] + 3.0.1 (2023-10-30) ------------------ @@ -53,6 +57,7 @@ The ASDF Standard is at v1.6.0 (leaf) nodes if ``show_values`` is enabled [#1687] - Deprecate ``asdf.util.is_primitive`` [#1687] + 3.0.0 (2023-10-16) ------------------ diff --git a/asdf/_display.py b/asdf/_display.py index d3d665bfc..4418a0393 100644 --- a/asdf/_display.py +++ b/asdf/_display.py @@ -257,7 +257,17 @@ def _render_node_value(self, info): return f"({rendered_type}): shape={info.node.shape}, dtype={info.node.dtype.name}" if not info.children and self._show_values: - return f"({rendered_type}): {info.node}" + try: + s = f"{info.node}" + except Exception: + # if __str__ fails, don't fail info, instead use an empty string + s = "" + # if __str__ returns multiple lines also use an empty string + if len(s.splitlines()) > 1: + s = "" + # if s is empty use the non-_show_values format below + if s: + return f"({rendered_type}): {s}" return f"({rendered_type})" diff --git a/asdf/_tests/test_info.py b/asdf/_tests/test_info.py index 79a89273d..fe4e114f4 100644 --- a/asdf/_tests/test_info.py +++ b/asdf/_tests/test_info.py @@ -665,3 +665,33 @@ def test_search(): result = af.search(value="hello") assert result.node == "hello" + + +def test_info_str(capsys): + class BadStr: + def __str__(self): + raise Exception() + + class NewlineStr: + def __str__(self): + return "a\nb" + + class CarriageReturnStr: + def __str__(self): + return "a\rb" + + class NiceStr: + def __str__(self): + return "nice" + + af = asdf.AsdfFile() + af["a"] = BadStr() + af["b"] = NewlineStr() + af["c"] = CarriageReturnStr() + af["d"] = NiceStr() + af.info() + captured = capsys.readouterr() + assert "(BadStr)\n" in captured.out + assert "(NewlineStr)\n" in captured.out + assert "(CarriageReturnStr)\n" in captured.out + assert "(NiceStr): nice\n" in captured.out