Skip to content

Commit 06a6678

Browse files
authored
Merge pull request #832 from HEXRD/np-load-context-manager
Use np.load() within a context manager
2 parents 867b436 + 6ddbe55 commit 06a6678

File tree

1 file changed

+17
-14
lines changed

1 file changed

+17
-14
lines changed

hexrd/imageseries/load/framecache.py

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,10 @@ def _load_cache_fch5(self):
8888
unwrap_h5_to_dict(file["metadata"], self._meta)
8989

9090
def _load_cache_npz(self):
91-
arrs = np.load(self._fname)
91+
with np.load(self._fname) as arrs:
92+
self._load_cache_npz_arrays(arrs)
93+
94+
def _load_cache_npz_arrays(self, arrs: np.lib.npyio.NpzFile):
9295
# HACK: while the loaded npz file has a getitem method
9396
# that mimicks a dict, it doesn't have a "pop" method.
9497
# must make an empty dict to pop after assignment of
@@ -266,19 +269,19 @@ def _load_framecache_npz(
266269
) -> list[csr_array]:
267270

268271
framelist = []
269-
arrs = np.load(filepath)
270-
for i in range(num_frames):
271-
row = arrs[f"{i}_row"]
272-
col = arrs[f"{i}_col"]
273-
data = arrs[f"{i}_data"]
274-
frame = csr_array((data, (row, col)),
275-
shape=shape,
276-
dtype=dtype)
277-
278-
# Make the data unwriteable, so we can be sure it won't be modified
279-
frame.data.flags.writeable = False
280-
281-
framelist.append(frame)
272+
with np.load(filepath) as arrs:
273+
for i in range(num_frames):
274+
row = arrs[f"{i}_row"]
275+
col = arrs[f"{i}_col"]
276+
data = arrs[f"{i}_data"]
277+
frame = csr_array((data, (row, col)),
278+
shape=shape,
279+
dtype=dtype)
280+
281+
# Make the data unwriteable, so we can be sure it won't be modified
282+
frame.data.flags.writeable = False
283+
284+
framelist.append(frame)
282285

283286
return framelist
284287

0 commit comments

Comments
 (0)