-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcacheWithFile.py
More file actions
32 lines (30 loc) · 841 Bytes
/
cacheWithFile.py
File metadata and controls
32 lines (30 loc) · 841 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
'''
````python
@cacheWithFile('expanded_matrix')
def expandMatrix(m):
# some heavy computation
result = ...
return result
````
'''
import pickle
class cacheWithFile:
def __init__(self, name, force_recompute=False):
self.name = name + '.pickle'
self.force_recompute = force_recompute
def __call__(self, func):
try:
if self.force_recompute:
raise FileNotFoundError
with open(self.name, 'rb') as f:
result = pickle.load(f)
except FileNotFoundError:
def f(*a, **kw):
result = func(*a, **kw)
with open(self.name, 'wb') as f:
pickle.dump(result, f)
return result
else:
def f(*_, **__):
return result
return f