0

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?

chris
  • 7,222
  • 5
  • 31
  • 37
  • I'm the `klepto` author. I'm not clear what you are looking for. Do you want both `func1` and `func2` to cache to the same `dir_archive`… but the "sub-caches" to remain distinct for each function? If that's the case why not just use two different directories? Basically, cache function `func1` in directory `./func1` and function `func2` in `./func2`? All you'd need to add is `name='func1'` for the first `dir_archive` and `name='func2'` for the second. – Mike McKerns Jan 05 '16 at 19:01
  • Hi there, I'm looking to make the name of the function part of the key of the cahe, as well as the args. Then I can use the same archive without using name. – chris Jan 05 '16 at 22:20

1 Answers1

0

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.

Mike McKerns
  • 33,715
  • 8
  • 119
  • 139