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

Make InMemoryGroup provide more informative reprs #319

Merged
merged 1 commit into from
Apr 30, 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
27 changes: 27 additions & 0 deletions versioned_hdf5/tests/test_wrappers.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@
from ..wrappers import InMemoryArrayDataset, InMemoryGroup, InMemorySparseDataset


@pytest.fixture()
def premade_group(h5file):
group = h5file.create_group("group")
return InMemoryGroup(group.id)


def test_InMemoryArrayDataset(h5file):
group = h5file.create_group("group")
parent = InMemoryGroup(group.id)
Expand Down Expand Up @@ -107,3 +113,24 @@ def test_InMemoryArrayDataset_resize_multidimension(oldshape, newshape, h5file):
)
h5file["data"].resize(newshape)
assert_equal(dataset[()], h5file["data"][()], str(newshape))


def test_group_repr(premade_group):
"""Test that repr(InMemoryGroup) also shows reprs of child objects."""
foo = premade_group.create_dataset(
"foo",
data=np.array([1, 2, 3, 4, 5, np.nan]),
)
bar = premade_group.create_dataset(
"bar",
data=np.array([1, 2, 3, 4, 5, np.nan]),
)
baz = premade_group.create_dataset(
"baz",
data=np.array([1, 2, 3, 4, 5, np.nan]),
)

result = repr(premade_group)
assert repr(foo) in result
assert repr(bar) in result
assert repr(baz) in result
16 changes: 9 additions & 7 deletions versioned_hdf5/wrappers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"""

import posixpath
import textwrap
import warnings
from collections import defaultdict
from weakref import WeakValueDictionary
Expand Down Expand Up @@ -66,15 +67,16 @@ def close(self):

# Based on Group.__repr__
def __repr__(self):
namestr = ('"%s"' % self.name) if self.name is not None else "(anonymous)"
namestr = f'"{self.name}"' if self.name is not None else "(anonymous)"
if not self:
r = "<Closed InMemoryGroup>"
elif self._committed:
r = "<Committed InMemoryGroup %s>" % namestr
else:
r = "<InMemoryGroup %s (%d members)>" % (namestr, len(self))
return "<Closed InMemoryGroup>"
if self._committed:
return f"<Committed InMemoryGroup {namestr}>"

return r
text = [f"<InMemoryGroup {namestr} ({len(list(self))} members)>"]
for item in self.values():
text.append(textwrap.indent(repr(item), prefix=" "))
return "\n".join(text)

def _check_committed(self):
if self._committed:
Expand Down
Loading