0

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.

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

Although this is correct but, it would be better if you explain why the code in OP doesn't work and why yours works. People who see this answer later will benefit from the explanation.
0

A dictionary in python has some pre-requisites for it's keys, see: https://wiki.python.org/moin/DictionaryKeys

The solution is to convert the arguments from various types into hasheable type, like string.

During the course maybe they used different arguments than you. Which worked until they were "reasonable" hasheable types.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.