Is frozenset adequate for caching of symmetric input data in a python dict?

Posted by Debilski on Stack Overflow See other posts from Stack Overflow or by Debilski
Published on 2010-04-03T22:32:35Z Indexed on 2010/04/03 22:33 UTC
Read the original article Hit count: 315

Filed under:
|
|
|

The title more or less says it all:

I have a function which takes symmetric input in two arguments, e.g. something like

def f(a1, a2):
    return heavy_stuff(abs(a1 - a2))

Now, I want to introduce some caching method. Would it be correct / pythonic / reasonably efficient to do something like this:

cache = {}
def g(a1, a2):
    return cache.setdefault(frozenset((tuple(a1), tuple(a2))), f(a1, a2))

Or would there be some better way?

© Stack Overflow or respective owner

Related posts about python

Related posts about sets