-
Notifications
You must be signed in to change notification settings - Fork 29
/
_imcache.py
51 lines (37 loc) · 1.15 KB
/
_imcache.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
# -*- coding: utf-8 -*-
"""Read and write to a dict-like cache."""
from collections import MutableMapping
class IMCache(MutableMapping):
"""Read and write to a dict-like cache."""
MAXLEN = 1000
# pylint: disable=keyword-arg-before-vararg
def __init__(self, maxlen=MAXLEN, *a, **k):
self.filepath = 'IN MEMORY'
self.maxlen = maxlen
self.d = dict(*a, **k)
while len(self) > maxlen: # pragma: no cache
self.popitem()
def __iter__(self):
return iter(self.d)
def __len__(self):
return len(self.d)
def __getitem__(self, k):
return self.d[k]
def __setitem__(self, k, v):
if k not in self and len(self) == self.maxlen:
self.popitem()
self.d[k] = v
def __contains__(self, key):
return key in self.d
def __delitem__(self, k):
del self.d[k]
def __bool__(self):
return len(self) != 0
# For PY2 compatibility
__nonzero__ = __bool__
def __call__(self, k):
"""Implement function call operator."""
try:
return self.__getitem__(k)
except KeyError:
return None