python decorator

Pavol Lisy pavol.lisy at gmail.com
Wed Feb 22 10:16:06 EST 2017


On 2/22/17, Steve D'Aprano <steve+python at 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)



More information about the Python-list mailing list