Search code examples
pythonklepto

use klepto to cache by function name and args


I'm trying to use klepto as a cache which hashes off the args and function name, is this possible?

e.g. so using a dir_cache i would be able to

@inf_cache(cache=dir_archive(cached=False))
def func1(x, y):
    return x + y

@inf_cache(cache=dir_archive(cached=False))
def func2(x, y):
    return x - y

and both calls to func1(1, 2) and func2(1, 2) would result in separate keys in the dir_archive

am i missing something?


Solution

  • Although probably not a totally robust solution, this seems to do what you want at some level.

    >>> import klepto 
    >>> @klepto.inf_cache(cache=klepto.archives.dir_archive(cached=False))
    ... def func1(x, y, name='func1'):
    ...   return x+y
    ... 
    >>> @klepto.inf_cache(cache=klepto.archives.dir_archive(cached=False))
    ... def func2(x, y, name='func2'):
    ...   return x-y
    ... 
    >>> 
    >>> func1(1,2)
    3
    >>> func1(1,3)
    4
    >>> func2(2,4)
    -2
    >>> func2(1,2)
    -1
    >>> func1.__cache__()
    dir_archive('memo', {-8532897055064740991: 4, -8532897055063328358: 3, -960590732667544693: -1, -3289964007849195004: -2}, cached=False)
    >>> 
    >>> func1(1,2)        
    3
    >>> func1(1,2)
    3
    >>> func2(1,2)
    -1
    >>> 
    >>> func1.__cache__() == func2.__cache__()
    True
    

    You'll note that the dir_archive is the same, and the functions both appear to use individual caches. One issue, would be that you could pass in a 'name' to override the default, and mess things up easily. I'm guessing that you could do something more robust if needed with another decorator to prevent the user from changing the 'name' keyword.