Reputation: 48466
I want to cache certain methods of a class - but only if a read_only
flag is set on the instance of the class.
So, in the object below, I want the get()
method to be cacheable, but only if self.readonly
is True.
I can't conditionally use the decorator, because it's set when the class is defined, not when it's instantiated.
from beaker.cache import cache_regions, cache_region
cache_regions.update({
'long_term':{
'expire':86400,
'type':'dbm',
'data_dir':'/tmp',
'key_length': 32,
}
})
class Foo(object):
def __init__(self, read_only=True):
self.read_only = read_only
@cache_region('long_term')
def get(self, arg):
return arg + 1
Upvotes: 4
Views: 2105
Reputation: 33407
You can use a decorator to call the right (cached or not) function checking the desired attribute:
def conditional(decorator):
def conditional_decorator(fn):
dec = decorator(fn)
def wrapper(self, *args, **kw):
if self.read_only:
return dec(self, *args, **kw)
return fn(self, *args, **kw)
return wrapper
return conditional_decorator
Use like this:
@conditional(cache_region('long_term'))
def get(self, arg):
return arg + 1
Upvotes: 3