Search code examples
pythonfunctionpython-decorators

Call this memoized function raises TypeError: unhashable type: 'dict'


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'


Solution

  • 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))