Created
January 6, 2020 08:55
-
-
Save allenyang79/ee8806f7d218fee40863a767f1492edd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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