Skip to content

Instantly share code, notes, and snippets.

@lightyears1998
Last active November 28, 2021 03:59
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 lightyears1998/2bc643fda942e8418bd6434f6b8c744f to your computer and use it in GitHub Desktop.
Save lightyears1998/2bc643fda942e8418bd6434f6b8c744f to your computer and use it in GitHub Desktop.
Python caching with decorator
import random
from functools import wraps
disk = dict()
def read_cache(path):
return disk.get(path, None)
def write_cache(path, data):
disk[path] = data
def caching(cache_path_builder):
def cache_path_wrapper(func):
@wraps(func)
def cache_wrapper(*arg, **kwargs):
cache_path = cache_path_builder(*arg)
force_update = kwargs.pop('force_update', False)
no_cache = kwargs.pop('no_cache', False)
cached_result = read_cache(cache_path) if not force_update else None
if cached_result:
return cached_result, True
else:
result = func(*arg, **kwargs)
if not no_cache:
write_cache(cache_path, result)
return result, False
return cache_wrapper
return cache_path_wrapper
@caching(lambda range: str(range))
def get_random_number(range):
"""I return a random number.
After decorating with @caching(...), I return a tuple `ret`,
which `ret[0]` is the random number and `ret[1]` indicates whether cache is used.
"""
return random.randint(0, range)
if __name__ == "__main__":
print("__doc__", get_random_number.__doc__)
print("\n#1")
print(get_random_number(100)) #1
print(get_random_number(100, force_update=True, no_cache=True)) #2
print(get_random_number(100)) #3, same with #1
print(get_random_number(100)) #4, same with #1
print(get_random_number(100, force_update=True)) #4
print(get_random_number(100)) #5, same with #4
print("\n#2")
print(get_random_number(200)) #6
print(get_random_number(200)) #7, same with #6
__doc__ I return a random number.
After decorating with @caching(...), I return a tuple `ret`,
which `ret[0]` is the random number and `ret[1]` indicates whether cache is used.
#1
(38, False)
(12, False)
(38, True)
(38, True)
(43, False)
(43, True)
#2
(130, False)
(130, True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment