Skip to content

Commit

Permalink
Fix/h5store setdefault (#180)
Browse files Browse the repository at this point in the history
* Extend unit test to check H5Store.setdefault() return value.

* Add explicit setdefault() functions to H5Store and H5Group.

This ensures that for example, the return value of
`h5store.setdefault('foo', dict())` is an instance of `H5Group` and
not just a dictionary.

* Update changelog.
  • Loading branch information
csadorf committed Apr 30, 2019
1 parent d0aaf64 commit b35cc5c
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
1 change: 1 addition & 0 deletions changelog.txt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ next

- Add command line options ``--sp`` and ``--doc`` for ``signac find`` that allow users to display key-value pairs of the state point and document in combination with the job id (#97, #146).
- Fix: Searches for whole numbers will match all numerically matching integers regardless of whether they are stored as decimals or whole numbers (#169).
- Fix: Passing an instance of dict to `H5Store.setdefault()` will return an instance of `H5Group` instead of a dict (#180).


[1.0.0] -- 2019-02-28
Expand Down
8 changes: 8 additions & 0 deletions signac/core/h5store.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,10 @@ def __setattr__(self, key, value):
else:
self.__setitem__(key, value)

def setdefault(self, key, value):
super(H5Group, self).setdefault(key, value)
return self.__getitem__(key)

def __iter__(self):
# The generator below should be refactored to use 'yield from'
# once we drop Python 2.7 support.
Expand Down Expand Up @@ -433,6 +437,10 @@ def __delattr__(self, key):
else:
self.__delitem__(key)

def setdefault(self, key, value):
super(H5Store, self).setdefault(key, value)
return self.__getitem__(key)

def __iter__(self):
with _ensure_open(self):
# The generator below should be refactored to use 'yield from'
Expand Down
6 changes: 5 additions & 1 deletion tests/test_h5store.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,11 @@ def test_set_get_explicit_nested(self):
with self.open_h5store() as h5s:
key = 'setgetexplicitnested'
d = self.get_testdata()
h5s.setdefault('a', dict())
self.assertNotIn('a', h5s)
ret = h5s.setdefault('a', dict())
self.assertIn('a', h5s)
self.assertEqual(ret, h5s['a'])
self.assertTrue(hasattr(ret, '_store')) # is an H5Group object
child1 = h5s['a']
child2 = h5s['a']
self.assertEqual(child1, child2)
Expand Down

0 comments on commit b35cc5c

Please sign in to comment.