Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I have the below code and when i try to print i am getting the error, can someone tell me how to fix it?

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'

1 Answer

0 votes
by (36.8k points)

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

I got the idea from that Memoize section of each 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))

 Want to be a master in Data Science? Enroll in this Data Scientist

Related questions

0 votes
1 answer
0 votes
0 answers
asked Jun 24, 2021 in Python by priyavishnu16 (120 points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...