python decorator

Cameron Simpson cs at zip.com.au
Wed Feb 22 02:19:36 EST 2017


On 21Feb2017 22:44, alfredocabrera4 at gmail.com <alfredocabrera4 at gmail.com> wrote:
>I have a python function and a decorator that works just fine.
>
>def fun_cache(function):
>    memo = {}
>    def wrapper(*args):
>        if args in memo:
>            return memo[args]
>        else:
>            rv = function(*args)
>            memo[args] = rv
>            return rv
>    return wrapper
>
>
>@fun_cache
>def fib(n):
>    if (n < 2): return 1
>    else: return fib(n-1) + fib(n-2)
>
>assert(fib(0) == 1)
>assert(fib(3) == 3)
>assert(fib(6) == 13)
>assert(fib(10) == 89)
>assert(fib(30) == 1346269)
>assert(fib(100) == 573147844013817084101)
>assert(fib(400) == 284812298108489611757988937681460995615380088782304890986477195645969271404032323901)
>
>
>Now I will like to call the @fun_cache decorator like this :
>
>@fun_cache(cache={})
>
>Any help?

You need to write "fun_cache" as a function accepting a cache argument, and 
returning a decorator that uses that cache.

Like:

    def fun_cache(cache):
        def fun_cache_decorator(function):
            def wrapper(*args):
                ... save things in cache instead of memo ...
            return wrapper
        return fun_cache_decorator

Cheers,
Cameron Simpson <cs at zip.com.au>



More information about the Python-list mailing list