How to cache a function with both position and keyword parameters?

Viewed 60

I have a function foo(a, b, c= False, d = 0), and I need to create a cache dict inside the function for each combination of the parameters.

The examples I have seen online only use *args, but I need to get the kwargs-values too, in the correct order, and store them in a cache dict, and handle the case that dicts cannot be keys, and kwargs is a dict.

So I did it like this: is this the way to go?

foo(*args, **kwargs):
     if (*args, *kwargs.values()) in cache:
         return cache[(*args, *kwargs.values())]

Basically I convert the kwargs to values (in the order of insertion since I am using Python3.6, which will be what I want) and then combine with *args to create a tuple.

0 Answers
Related