forked from d2iq-archive/marathon-lb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlrucache.py
More file actions
29 lines (24 loc) · 723 Bytes
/
lrucache.py
File metadata and controls
29 lines (24 loc) · 723 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
#!/usr/bin/env python3
"""
A simple LRU cache based on the one described at:
https://www.kunxi.org/blog/2014/05/lru-cache-in-python/
"""
import collections
class LRUCache:
def __init__(self, capacity=100):
self.capacity = capacity
self.cache = collections.OrderedDict()
def get(self, key, default):
try:
value = self.cache.pop(key)
self.cache[key] = value
return value
except KeyError:
return default
def set(self, key, value):
try:
self.cache.pop(key)
except KeyError:
if len(self.cache) >= self.capacity:
self.cache.popitem(last=False)
self.cache[key] = value