Created
December 28, 2022 01:54
-
-
Save phrz/aac1bf6db0ae6cc5774241fbd35f9c82 to your computer and use it in GitHub Desktop.
Caching to file with a decorator
This file contains hidden or 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
def cache_to_file(file_name): | |
def decorator(f): | |
try: | |
cache = json.load(open(file_name, 'r')) | |
except (IOError, ValueError): | |
cache = {} | |
def new_func(*args, **kwargs): | |
cache.update({ps:f(*args,**kwargs)}) if (ps := param_string(args, kwargs)) not in cache else (json.dump(cache, open(file_name, 'w'))) | |
return cache[ps] | |
return new_func | |
return decorator | |
@cache_to_file('rank_cache.json') | |
def rank(a, b): | |
print(f'\nA: {a}\nB: {b}') | |
choice = None | |
while not choice or not (csu := choice.strip().upper()) in {'A','B'}: | |
choice = input('Which is better, A or B? [A/B] ') | |
if csu == 'A': | |
return 1 # A > B | |
elif csu == 'B': | |
return -1 # A < B |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment