Skip to content

Instantly share code, notes, and snippets.

@allenyang79
Created January 3, 2020 04:05
Show Gist options
  • Save allenyang79/044043e3668ec3490626d2dfa3fa3bf5 to your computer and use it in GitHub Desktop.
Save allenyang79/044043e3668ec3490626d2dfa3fa3bf5 to your computer and use it in GitHub Desktop.
import time
import wrapt
import contextlib
import weakref
import functools
class Cacher:
def __init__(self):
self.meta = {}
self.cache = {}
def wrapper(self, fn, keyfn):
@functools.wraps(fn)
def wrapped(*args, **kw):
key = keyfn(*args, **kw)
if key in self.cache[wrapped]:
print("cached", wrapped.__name__, *args, **kw)
return self.cache[wrapped][key]
ret = fn(*args, **kw)
self.cache[wrapped][key] = ret
return ret
self.meta[wrapped] = keyfn
self.cache[wrapped] = {}
return wrapped
def cache_it(self, keyfn):
return functools.partial(self.wrapper, keyfn=keyfn)
def pre_cache_it(self, wrapped, result, args, kw):
keyfn = self.meta.get(wrapped)
key = keyfn(*args, **kw)
self.cache[wrapped][key] = result
cacher = Cacher()
@cacher.cache_it(keyfn=lambda a, b: f'{a}:{b}')
def foo(a, b) -> int:
time.sleep(1)
return a + b
@cacher.cache_it(keyfn=lambda a, b: f'{a}:{b}')
def bar(a, b) -> int:
time.sleep(1)
return a * b
print(foo(10, 20))
print(foo(10, 20))
print(bar(10, 20))
print(bar(10, 20))
print(foo(10, 20))
print(foo(10, 20))
print(foo(10, 20))
print(bar(10, 20))
print(bar(10, 20))
print(bar(10, 20))
print(foo.__annotations__)
print(foo.__annotations__)
print(bar(10, 20))
cacher.pre_cache_it(bar, 199, (), {'a':10, 'b': 20})
print(bar(10, 20))
print(bar(10, 20))
print(bar(10, 20))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment