2

I have this code and when I print it out I have this error. Can someone tell me how to fix this?

def memoize(func):
    """Store the results of the decorated function for fast lookup
    """
    # Store results in a dict that maps arguments to results
    cache = {}
    def wraper(*args, **kwargs):
        if (args, kwargs) not in cache:
            cache[(args, kwargs)] = func(*args, **kwargs)
        return cache[(args, kwargs)]
    return wraper

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

print(slow_function(3,4))

Error: TypeError: unhashable type: 'dict'

martineau
  • 119,623
  • 25
  • 170
  • 301
Daniel ML
  • 23
  • 2

1 Answers1

3

Here's a simple way to avoid the problem by converting the kwargs dictionary into a string (along with args), to make an acceptable dictionary key.

I got the idea from the Memoize section of the Python Decorator Library.

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 = {}
    def wrapper(*args, **kwargs):
        key = str(args) + str(kwargs)
        if key not in cache:
            cache[key] = func(*args, **kwargs)
        return cache[key]
    return wrapper

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

print(slow_function(3,4))
martineau
  • 119,623
  • 25
  • 170
  • 301
  • But why doesn't the origianl code work? I met the same code intended to work at DataCamp course on functions as well as at the other resorces. – Andrew Anderson Oct 18 '22 at 11:07