Skip to content

Commit f35ef5d

Browse files
committed
ENH: make sure files are properly closed even when an Exception is raised during load
1 parent 2a057b9 commit f35ef5d

File tree

1 file changed

+18
-16
lines changed

1 file changed

+18
-16
lines changed

larray/inout/common.py

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -137,22 +137,24 @@ def read(self, keys, *args, display=False, ignore_exceptions=False, **kwargs) ->
137137
Dictionary containing the loaded objects.
138138
"""
139139
self._open_for_read()
140-
metadata = self._read_metadata()
141-
item_types = self.item_types()
142-
if keys is not None:
143-
item_types = {key: type_ for key, type_ in item_types.items() if key in keys}
144-
res = {}
145-
for key, type_ in item_types.items():
146-
if display:
147-
print("loading", type_, "object", key, "...", end=' ')
148-
try:
149-
res[key] = self._read_item(key, type_, *args, **kwargs)
150-
except Exception:
151-
if not ignore_exceptions:
152-
raise
153-
if display:
154-
print("done")
155-
self.close()
140+
try:
141+
metadata = self._read_metadata()
142+
item_types = self.item_types()
143+
if keys is not None:
144+
item_types = {key: type_ for key, type_ in item_types.items() if key in keys}
145+
res = {}
146+
for key, type_ in item_types.items():
147+
if display:
148+
print("loading", type_, "object", key, "...", end=' ')
149+
try:
150+
res[key] = self._read_item(key, type_, *args, **kwargs)
151+
except Exception:
152+
if not ignore_exceptions:
153+
raise
154+
if display:
155+
print("done")
156+
finally:
157+
self.close()
156158
return metadata, res
157159

158160
def dump(self, metadata, values, *args, display=False, **kwargs):

0 commit comments

Comments
 (0)