简体   繁体   中英

Creating a Memoize decorator on python using cache

I'm using Datacamp course to learn about decorators and I admit I'm pretty new to the topic of caches.

What has got me stuck is I'm following the "example" memoization decorator on their course and it throws an error on jupyter notebook even though its exactly the same as on their course:

def memoize(func):
    '''Store the results of the decorated function for fast look up'''
    #Store results in a dict that maps arguments to results
    cache = {}
    #As usual, create the wrapper to create the newly decorated function
    def wrapper(*args, **kwargs):
        # If these arguments havent been seen before...
        if (args, kwargs) not in cache:
            #Call func() and store the result.
            cache[(args, kwargs)] =func(*args, **kwargs)
        #Now we can look them up quickly
        return cache[(args, kwargs)]
    
    return wrapper 

I use the decorator with the following function:

@memoize
def slow_function(a,b):
    print('Sleeping...')
    time.sleep(5)
    return a+b

The error is unhashable type dict. If anyone could explain the reason for this error I would be very grateful.

Thanks in advance.

Try this:

import time

def memoize(func):
    """
    Store the results of the decorated function for fast lookup
    """
    # store results in a dict that maps arguments to results
    cache = {}
    # define the wrapper function to return
    def wrapper(*args, **kwargs):
        # if these arguments haven't been seen before
        if (str(args), str(kwargs)) not in cache:
            # call func() and store the result
            cache[(str(args), str(kwargs))] = func(*args, **kwargs)
        return cache[(str(args), str(kwargs))]
    return wrapper


@memoize
def slow_function(a, b):
    print('Sleeping...')
    time.sleep(5)
    return a + b

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM