Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Caching: TypeError: unhashable type: 'dict' [duplicate]

I am trying to implement a caching function in Python. The code looks like 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 wrapper(*args, **kwargs):
        # If these arguments haven't been seen before, call func() and store the result.
        if (args, kwargs) not in cache:        
            cache[(args, kwargs)] = func(*args, **kwargs)          
        return cache[(args, kwargs)]

    return wrapper

@memoize
def add(a, b):
    print('Sleeping...')
    return a + b

add(1, 2)

When I run the code, I get TypeError: unhashable type: 'dict'.

What's wrong?

like image 521
Cody Avatar asked Oct 20 '25 09:10

Cody


1 Answers

The key of a dict must be hashable. You provide an unhashable key (args,kwargs) since kwargs is a dict which is unhashable.

To solve this problem, you should generate a hashable key from the combination of args and kwargs. For example, you can use (assuming all values of args and kwargs are hashable)

key = ( args , tuple((kwargs.items())))

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):
        # If these arguments haven't been seen before, call func() and store the result.
        key = ( args , tuple((kwargs.items())))
        if key not in cache:        
            cache[key] = cc = func(*args, **kwargs)          
            return cc
        return cache[key]

    return wrapper

@memoize
def add(a, b):
    print('Sleeping...')
    return a + b

print(add(1, 2))
like image 68
napuzba Avatar answered Oct 21 '25 23:10

napuzba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!