Skip to content

Instantly share code, notes, and snippets.

@allenyang79
Created January 6, 2020 08:55
Show Gist options
  • Save allenyang79/ee8806f7d218fee40863a767f1492edd to your computer and use it in GitHub Desktop.
Save allenyang79/ee8806f7d218fee40863a767f1492edd to your computer and use it in GitHub Desktop.
import time
import wrapt
import random
import weakref
def cache_it(keyfn):
cache = weakref.WeakKeyDictionary()
@wrapt.decorator
def pass_through(wrapped, instance, args, kwargs):
if instance not in cache:
print("put", instance.name)
cache[instance] = {}
key = (wrapped.__name__, keyfn(*args, **kwargs))
if key in cache[instance]:
print('cache', list(cache.items()))
return cache[instance][key]
ret = wrapped(*args, **kwargs)
cache[instance][key] = ret
return ret
pass_through.__cache = cache
return pass_through
class Calculator:
def __init__(self):
self.name = f'name_{random.randint(0, 100)}'
@cache_it(keyfn=lambda a, b: f"add:{a}:{b}")
def add(self, a, b):
return a + b + random.random()
def main():
cal = Calculator()
# print(cal)
# print(cal.add(3, 5))
# print(cal.add(3, 5))
# print(cal.add(3, 5))
# print(cal.add(3, 6))
# print(cal.add(3, 7))
cal.add(1, 3)
cal.add(1, 3)
cal.add(2, 4)
cal.add(2, 4)
cal_b = Calculator()
cal_b.add(2, 3)
cal_b.add(3, 4)
cal_b.add(2, 3)
cal_b.add(3, 4)
# print(cal_b)
# print(cal_b.add(3, 5))
# print(cal_b.add(3, 5))
main()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment