How would I write a decorator like this. I want to be able to specify the value for max_hits when I call the decorator (or optionally leave it out).
E.g., the desired use would be
@memoize(max_hits=7)
def a(val):
print val
or
@memoize
def a(val):
print val
(Using the first example gives an error about incorrect arguments.)
Decorator:
class memoize:
"""A decorator to cache previosly seen function inputs.
usage:
@memoize
def some_func(..
"""
def __init__(self, function, max_hits=None):
self.max_hits = max_hits
self.function = function
self.memoized = {}
def __call__(self, *args, **kwargs):
key = (args,tuple(kwargs.items()))
try:
return self.memoized[key]
except KeyError:
self.memoized[key] = self.function(*args,**kwargs)
return self.memoized[key]
You have to make
memoizea function that takes an optional argumentmax_hitsand returns a decorator (i.e. another callable object that will take the function as the first argument); in this case, you can use the following two syntaxes:So, probably something along the lines of:
Note that
@memoize()will work but your originally desired@memoizesyntax won’t; in the latter case, the function you are decorating with@memoizewould be passed tomemoizeas the first argument (max_hits). If you want to treat this case, you can extendmemoizeas follows: