-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom_cache.py
More file actions
70 lines (57 loc) · 1.9 KB
/
custom_cache.py
File metadata and controls
70 lines (57 loc) · 1.9 KB
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
import datetime
class CustomCache:
def __init__(self, max_size=100):
"""Constructor"""
self.cache = {}
self.max_cache_size = max_size
def __call__(self, function):
def wrapper(*args, **kwargs):
key = str(args) + str(kwargs)
if key in self.cache:
return self.cache[key]['value']
value = function(*args, **kwargs)
if value:
self.update(key, value)
return value
return wrapper
def __contains__(self, key):
"""
Returns True or False depending on whether or not the key is in the cache
"""
return key in self.cache
def update(self, key, value):
"""
Update the cache dictionary and optionally remove the oldest item
"""
if key not in self.cache and len(self.cache) >= self.max_cache_size:
self.remove_oldest()
self.cache[key] = {'date_accessed': datetime.datetime.now(), 'value': value}
def update_key(self, value, *args, **kwargs):
"""
Update specific key in cache just in case
"""
key = str(args) + str(kwargs)
if key in self.cache:
self.cache[key] = {'date_accessed': datetime.datetime.now(), 'value': value}
def remove_oldest(self):
"""
Remove the entry that has the oldest accessed date
"""
oldest_entry = None
for key in self.cache:
if oldest_entry is None:
oldest_entry = key
elif self.cache[key]['date_accessed'] < self.cache[oldest_entry]['date_accessed']:
oldest_entry = key
self.cache.pop(oldest_entry)
def cache_clear(self):
"""
Clear entire cache
"""
self.cache = {}
@property
def size(self):
"""
Return the size of the cache
"""
return len(self.cache)