Skip to content

Commit 6cb1277

Browse files
committed
Add cache_root context manager
1 parent 9291b51 commit 6cb1277

File tree

3 files changed

+36
-7
lines changed

3 files changed

+36
-7
lines changed

README.md

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -170,13 +170,9 @@ class Tester(Wcache):
170170

171171
return res
172172

173-
# This will set the root directory where cached data goes
174-
# The data will go to `/some/directory/Tester`
175-
# This has to be done ONCE and only ONCE.
176-
Wcache.set_cache_root(root='/some/directory')
177-
178-
obj = Tester(nval=3)
179-
...
173+
with Cache.cache_path(path='/some/directory')
174+
obj = Tester(nval=3)
175+
...
180176
```
181177

182178
where the tester class has access to extra functionalities to:

src/dmu/workflow/cache.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,26 @@ def _context():
256256
return _context()
257257
# ---------------------------
258258
@classmethod
259+
def cache_root(cls, path : Path):
260+
'''
261+
Context manager used to set caching directory
262+
263+
Parameters
264+
----------------
265+
path: Path to directory where outputs will be cached
266+
'''
267+
old_val = cls._cache_root
268+
@contextmanager
269+
def _context():
270+
cls._cache_root = str(path)
271+
try:
272+
yield
273+
finally:
274+
cls._cache_root = old_val
275+
276+
return _context()
277+
# ---------------------------
278+
@classmethod
259279
def set_cache_root(cls, root : str | Path) -> None:
260280
'''
261281
Sets the path to the directory WRT which the _out_path_

tests/worflow/test_cache.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import os
55
import pytest
66

7+
from pathlib import Path
78
from dmu.generic import utilities as gut
89
from dmu.workflow.cache import Cache as Wcache
910
from dmu.logging.log_store import LogStore
@@ -145,3 +146,15 @@ def test_cache_with_dir():
145146

146147
assert res == out
147148
# -----------------------------------
149+
def test_cache_context(tmp_path : Path):
150+
'''
151+
Tests setting caching directory through context manager
152+
'''
153+
log.info('')
154+
res = 4 * [1]
155+
156+
with Wcache.cache_root(path=tmp_path):
157+
obj = Tester(nval=4, name='cache_context')
158+
out = obj.run()
159+
160+
assert res == out

0 commit comments

Comments
 (0)