Skip to content

Commit 02dc70a

Browse files
authored
Merge pull request nexpy#265 from rayosborn:release-locks-on-error
Release file locks on close failure and clarify path errors
2 parents cb3c0c0 + 212cbbb commit 02dc70a

1 file changed

Lines changed: 13 additions & 9 deletions

File tree

src/nexusformat/nexus/tree.py

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -542,9 +542,11 @@ def __enter__(self):
542542

543543
def __exit__(self, *args):
544544
"""Close the NeXus file and, if necessary, release the lock."""
545-
if self._with_count == 1:
546-
self.close()
547-
self._with_count -= 1
545+
try:
546+
if self._with_count == 1:
547+
self.close()
548+
finally:
549+
self._with_count -= 1
548550

549551
def __del__(self):
550552
"""Close the file and delete the NXFile instance."""
@@ -721,9 +723,11 @@ def close(self):
721723
-----
722724
The file modification time of the root object is updated.
723725
"""
724-
if self.is_open():
725-
self._file.close()
726-
self.release_lock()
726+
try:
727+
if self.is_open():
728+
self._file.close()
729+
finally:
730+
self.release_lock()
727731
try:
728732
self._root._mtime = self.mtime
729733
except Exception:
@@ -4886,7 +4890,7 @@ def __getitem__(self, key):
48864890
try:
48874891
path = PurePath(str(key))
48884892
except TypeError:
4889-
raise NeXusError("Invalid index")
4893+
raise NeXusError(f"'{key}' is an invalid index")
48904894
if path.is_absolute():
48914895
node = self.nxroot
48924896
path = path.relative_to('/')
@@ -4896,7 +4900,7 @@ def __getitem__(self, key):
48964900
try:
48974901
node = node.entries[name]
48984902
except KeyError:
4899-
raise NeXusError("Invalid path")
4903+
raise NeXusError(f"'{path}' is an invalid path")
49004904
return node
49014905

49024906
def __setitem__(self, key, value):
@@ -5007,7 +5011,7 @@ def __delitem__(self, key):
50075011
if name in group:
50085012
group = group[name]
50095013
else:
5010-
raise NeXusError("Invalid path")
5014+
raise NeXusError(f"'{key}' is an invalid path")
50115015
if key not in group:
50125016
raise NeXusError("'"+key+"' not in "+group.nxpath)
50135017
elif group[key].is_linked():

0 commit comments

Comments
 (0)