2017-03-30 22:56:01 +00:00
|
|
|
import collections
|
2017-04-01 07:08:56 +00:00
|
|
|
|
2017-03-30 22:56:01 +00:00
|
|
|
class Cache:
|
2018-09-30 08:45:19 +00:00
|
|
|
def __init__(self, maxlen):
|
2017-03-30 22:56:01 +00:00
|
|
|
self.maxlen = maxlen
|
2018-09-30 08:45:19 +00:00
|
|
|
self.cache = collections.OrderedDict()
|
2017-03-30 22:56:01 +00:00
|
|
|
|
2018-03-19 03:58:00 +00:00
|
|
|
def __contains__(self, key):
|
2018-09-30 08:45:19 +00:00
|
|
|
return key in self.cache
|
2018-03-19 03:58:00 +00:00
|
|
|
|
2017-03-30 22:56:01 +00:00
|
|
|
def __getitem__(self, key):
|
2018-09-30 08:45:19 +00:00
|
|
|
value = self.cache.pop(key)
|
|
|
|
self.cache[key] = value
|
2017-03-30 22:56:01 +00:00
|
|
|
return value
|
|
|
|
|
2018-09-30 08:45:19 +00:00
|
|
|
def __len__(self):
|
|
|
|
return len(self.cache)
|
2017-03-30 22:56:01 +00:00
|
|
|
|
2018-09-30 08:45:19 +00:00
|
|
|
def __setitem__(self, key, value):
|
|
|
|
try:
|
|
|
|
self.cache.pop(key)
|
|
|
|
except KeyError:
|
|
|
|
if len(self.cache) >= self.maxlen:
|
|
|
|
self.cache.popitem(last=False)
|
|
|
|
self.cache[key] = value
|
2017-03-30 22:56:01 +00:00
|
|
|
|
2017-05-07 01:28:41 +00:00
|
|
|
def clear(self):
|
2018-09-30 08:45:19 +00:00
|
|
|
self.cache.clear()
|
2017-05-07 01:28:41 +00:00
|
|
|
|
2017-03-30 22:56:01 +00:00
|
|
|
def get(self, key, fallback=None):
|
|
|
|
try:
|
|
|
|
return self[key]
|
|
|
|
except KeyError:
|
|
|
|
return fallback
|
|
|
|
|
2018-09-30 08:45:19 +00:00
|
|
|
def pop(self, key):
|
|
|
|
return self.cache.pop(key)
|
|
|
|
|
2017-03-30 22:56:01 +00:00
|
|
|
def remove(self, key):
|
|
|
|
try:
|
2018-09-30 08:45:19 +00:00
|
|
|
self.pop(key)
|
2017-03-30 22:56:01 +00:00
|
|
|
except KeyError:
|
2018-09-30 08:45:19 +00:00
|
|
|
pass
|