-
Notifications
You must be signed in to change notification settings - Fork 10
/
cacheDecorators.py
78 lines (59 loc) · 1.6 KB
/
cacheDecorators.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
'''
'''
def d_initCache(f):
def __init__(*args, **kwargs):
self = args[0]
self._CACHE_ = {}
return f(*args, **kwargs)
__init__.__name__ = f.__name__
__init__.__doc__ = f.__doc__
return __init__
initCache = d_initCache
def d_cacheValue(f):
def cachedRetValFunc(*args, **kwargs):
self = args[0]
try:
return self._CACHE_[ f ]
except KeyError:
val = f(*args, **kwargs)
self._CACHE_[ f ] = val
return val
#it may be a parent class has caching turned on, but the child class does not...
except AttributeError:
return f(*args, **kwargs)
cachedRetValFunc.__name__ = f.__name__
cachedRetValFunc.__doc__ = f.__doc__
return cachedRetValFunc
cacheValue = d_cacheValue
def d_cacheValueWithArgs(f):
def cachedRetValFunc(*args, **kwargs):
self = args[0]
funcArgsTuple = (f.__name__,)+tuple(args[1:])
try:
return self._CACHE_[funcArgsTuple]
except KeyError:
val = f(*args, **kwargs)
self._CACHE_[funcArgsTuple] = val
return val
except TypeError:
return f(*args, **kwargs)
except AttributeError:
return f(*args, **kwargs)
cachedRetValFunc.__name__ = f.__name__
cachedRetValFunc.__doc__ = f.__doc__
return cachedRetValFunc
cacheValueWithArgs = d_cacheValueWithArgs
def d_resetCache(f):
def resetCacheFunc(*args, **kwargs):
self = args[ 0 ]
retval = f(*args, **kwargs)
try:
self._CACHE_.clear()
return retval
except AttributeError:
return retval
resetCacheFunc.__name__ = f.__name__
resetCacheFunc.__doc__ = f.__doc__
return resetCacheFunc
resetCache = d_resetCache
#end