Skip to content

Commit

Permalink
Merge pull request asdf-format#1748 from braingram/info_str
Browse files Browse the repository at this point in the history
info don't show value for bad __str__
  • Loading branch information
braingram authored Feb 27, 2024
2 parents 905e3c6 + e86dd14 commit fca8136
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
5 changes: 5 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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)
------------------

Expand All @@ -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)
------------------

Expand Down
12 changes: 11 additions & 1 deletion asdf/_display.py
Original file line number Diff line number Diff line change
Expand Up @@ -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})"

Expand Down
30 changes: 30 additions & 0 deletions asdf/_tests/test_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit fca8136

Please sign in to comment.