forked from diegomcarvalho/biocomp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
88 lines (70 loc) · 2.43 KB
/
utils.py
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import functools
from typing import Any
class Cache():
_table = dict()
def __init__(self) -> None:
self._table = dict()
def __getitem__(self, key):
try:
return self._table[key]
except KeyError:
raise KeyError(key)
def __setitem__(self, key, value):
self._table[key] = value
def __repr__(self) -> str:
return self._table.__repr__()
def getItem(self, key):
if key not in self._table.keys():
return None
else:
return self._table[key]
def tuplify(arguments: dict):
return tuple((k, tuple(v)) for k, v in arguments.items())
def app_reuse(cache, args_to_ignore):
"""Function to be used as decorator to allow the reuse (cache) of some apps functions.
At least until now, the apps need to contain only named arguments (kwargs)
Args:
cache (Cache's class object): Object to store the cache items
args_to_ignore (list): List containing the arguments to be ignored when caching
Example of use:
@app_reuse(cache=Cache(), args_to_ignore=["bar"])\\
def foo(bar):\\
return "foo" + str(bar)
"""
def decorator(func):
@functools.wraps(func)
def wrapper_decorator(*args, **kwargs):
filtered_kwargs = dict()
for kwarg in kwargs.keys():
if kwarg not in args_to_ignore:
filtered_kwargs[kwarg] = kwargs[kwarg]
t_args = tuplify(filtered_kwargs)
key= hash(t_args)
try:
value = cache[key]
if value:
print("Value is already in the cache")
return value
except KeyError:
ret = func(*args, **kwargs)
print("Value is not in the cache. Adding!")
cache[key] = ret
return ret
return wrapper_decorator
return decorator
class CircularList:
def __init__(self, slots: int) -> None:
if not slots:
raise ValueError
self.list = [None for _ in range(slots)]
self.index = 0
self.max_index = len(self.list) - 1
def next(self) -> Any:
if self.index == self.max_index:
self.index = 0
else:
self.index += 1
return self.list[self.index]
def current(self, value: Any) -> None:
self.list[self.index] = value
return