python decorator

Steve D'Aprano steve+python at pearwood.info
Wed Feb 22 05:35:48 EST 2017


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):
    ...



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list