Skip to content

Instantly share code, notes, and snippets.

@phrz
Created December 28, 2022 01:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phrz/aac1bf6db0ae6cc5774241fbd35f9c82 to your computer and use it in GitHub Desktop.
Save phrz/aac1bf6db0ae6cc5774241fbd35f9c82 to your computer and use it in GitHub Desktop.
Caching to file with a decorator
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