On 2/22/17, Steve D'Aprano <steve+pyt...@pearwood.info> wrote: > On Wed, 22 Feb 2017 08:47 pm, Cecil Westerhof wrote: > >> On Wednesday 22 Feb 2017 08:49 CET, Argentinian Black ops lll wrote: >> >>> *** SOLVED *** >> >> It would be nice if you shared the solution. > > I believe Cameron's post contains the bones of a solution. > > Here's my untested solution. > > > def func_cache(cache): > # Create a decorator that uses cache. > def decorate(function): > @functools.wraps(function) > def wrapper(*args): > try: > result = cache[args] > except KeyError: > result = function(*args) > cache[args] = result > except TypeError: > result = function(*args) > return result > return wrapper > return decorate > > > @func_cache({}): > def something(x): > ...
Maybe this technique could be reusable (and maybe part of functools?) With this decorator: def wrap_args(decorator): def decor_out(*args, **kwargs): def decor_in(func): return decorator(func, *args, **kwargs) return decor_in return decor_out Alfredo needs to change only (*) next 2 lines: def fun_cache(function): memo = {} to: @wrap_args def fun_cache(function, cache): memo = cache (*) - Steve's improvements (for example using functools.wraps) are good to consider as well! :) (but maybe catching TypeError could more problems hide than solve) -- https://mail.python.org/mailman/listinfo/python-list