Skip to content

Commit 41c3947

Browse files
committed
Fix and use context manager
1 parent d082ae9 commit 41c3947

2 files changed

Lines changed: 13 additions & 9 deletions

File tree

cobaya/likelihoods/base_classes/planck_2018_CamSpec_python.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -197,19 +197,13 @@ def init_params(self, ini, silent=False):
197197
)
198198
if not use_cache:
199199
self.covinv = np.linalg.inv(self.cov)
200-
elif os.path.exists(cache_file):
201-
self.covinv = np.load(cache_file).astype(np.float64)
202200
else:
203-
lock = FileLock()
204-
try:
205-
lock.set_lock(self.log, cache_file, wait=True)
201+
with FileLock(cache_file, log=self.log, wait=True):
206202
if os.path.exists(cache_file):
207203
self.covinv = np.load(cache_file).astype(np.float64)
208204
else:
209205
self.covinv = np.linalg.inv(self.cov)
210206
np.save(cache_file, self.covinv.astype(np.float32))
211-
finally:
212-
lock.clear_lock()
213207

214208
def get_foregrounds(self, data_params):
215209
sz_bandpass100_nom143 = 2.022

cobaya/output.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,13 @@ def use_portalocker():
5454
class FileLock:
5555
_file_handle: Any
5656

57-
def __init__(self, filename=None, log=None):
57+
def __init__(self, filename=None, log=None, **kwargs):
5858
self.lock_error_file = ""
5959
self.lock_file = ""
6060
if filename:
61-
self.set_lock(log, filename)
61+
self.set_lock(log, filename, **kwargs)
62+
else:
63+
assert not log and not kwargs
6264

6365
def set_lock(self, log, filename, force=False, wait=False):
6466
if self.has_lock():
@@ -176,6 +178,14 @@ def has_lock(self):
176178
def __del__(self):
177179
self.clear_lock()
178180

181+
def __enter__(self):
182+
return self
183+
184+
def __exit__(self, exception_type, exception_value, traceback):
185+
# Always clear any held lock; propagate original exceptions.
186+
self.clear_lock()
187+
return False
188+
179189

180190
class OutputReadOnly:
181191
"""

0 commit comments

Comments
 (0)