Skip to content

Commit 3a7da1c

Browse files
committed
Improved cache system
1 parent 0a43050 commit 3a7da1c

1 file changed

Lines changed: 55 additions & 7 deletions

File tree

sqlparse/utils.py

Lines changed: 55 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,60 @@
44
@author: piranna
55
'''
66

7+
try:
8+
from collections import OrderedDict
9+
except ImportError:
10+
OrderedDict = None
11+
12+
13+
if OrderedDict:
14+
class Cache(OrderedDict):
15+
"""Cache with LRU algorithm using an OrderedDict as basis
16+
"""
17+
def __init__(self, maxsize=100):
18+
OrderedDict.__init__(self)
19+
20+
self._maxsize = maxsize
21+
22+
def __getitem__(self, key, *args, **kwargs):
23+
# Remove the (key, value) pair from the cache, or raise KeyError
24+
value = self.pop(key)
25+
26+
# Insert the (key, value) pair on the front of the cache
27+
OrderedDict.__setitem__(self, key, value)
28+
29+
# Return the value from the cache
30+
return value
31+
32+
def __setitem__(self, key, value, *args, **kwargs):
33+
# Key was inserted before, remove it so we put it at front later
34+
if key in self:
35+
del self[key]
36+
37+
# Too much items on the cache, remove the least recent used
38+
elif len(self) >= self._maxsize:
39+
self.popitem(False)
40+
41+
# Insert the (key, value) pair on the front of the cache
42+
OrderedDict.__setitem__(self, key, value, *args, **kwargs)
43+
44+
else:
45+
class Cache(dict):
46+
"""Cache that reset when gets full
47+
"""
48+
def __init__(self, maxsize=100):
49+
dict.__init__(self)
50+
51+
self._maxsize = maxsize
52+
53+
def __setitem__(self, key, value, *args, **kwargs):
54+
# Reset the cache if we have too much cached entries and start over
55+
if len(self) >= self._maxsize:
56+
self.clear()
57+
58+
# Insert the (key, value) pair on the front of the cache
59+
dict.__setitem__(self, key, value, *args, **kwargs)
60+
761

862
def memoize_generator(func):
963
"""Memoize decorator for generators
@@ -13,7 +67,7 @@ def memoize_generator(func):
1367
Obviusly, this is only useful if the generator will always return the same
1468
values for each specific parameters...
1569
"""
16-
cache = {}
70+
cache = Cache()
1771

1872
def wrapped_func(*args, **kwargs):
1973
# params = (args, kwargs)
@@ -26,12 +80,6 @@ def wrapped_func(*args, **kwargs):
2680

2781
# Not cached, exec and store it
2882
except KeyError:
29-
# Reset the cache if we have too much cached entries and start over
30-
# In the future would be better to use an OrderedDict and drop the
31-
# Least Recent Used entries
32-
if len(cache) >= 10:
33-
cache.clear()
34-
3583
cached = []
3684

3785
for item in func(*args, **kwargs):

0 commit comments

Comments
 (0)