Skip to content

Commit

Permalink
Cache per class to avoid cache sharing with subclasses
Browse files Browse the repository at this point in the history
  • Loading branch information
MaartenKos committed Sep 4, 2015
1 parent 141ce6e commit 271710f
Showing 1 changed file with 15 additions and 11 deletions.
26 changes: 15 additions & 11 deletions social/backends/open_id.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,24 +277,28 @@ def __init__(self, handle, secret='', issued=0, lifetime=0, assoc_type=''):

class _cache(object):
"""
Cache decorator that caches the return value of a function or
method for a specified time.
Cache decorator that caches the return value of a method for a specified time.
It ignores the arguments of the cached function and always returns
the same value within the time range.
It maintains a cache per class, so subclasses have a different cache entry
for the same cached method.
Does not work for methods with arguments.
"""
def __init__(self, ttl):
self.ttl = ttl
self.value = None
self.last_update = None
self.cache = {}

def __call__(self, fn):
def wrapped(*args, **kwargs):
def wrapped(this):
now = time.time()
if not self.value or now - self.last_update > self.ttl:
self.value = fn(*args, **kwargs)
self.last_update = now
return self.value
last_updated = None
cached_value = None
if this.__class__ in self.cache:
last_updated, cached_value = self.cache[this.__class__]
if not cached_value or now - last_updated > self.ttl:
cached_value = fn(this)
self.cache[this.__class__] = (now, cached_value)
return cached_value
return wrapped


Expand Down

0 comments on commit 271710f

Please sign in to comment.