python decorator

alfredocabrera4 at gmail.com alfredocabrera4 at gmail.com
Wed Feb 22 01:44:42 EST 2017


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?



More information about the Python-list mailing list