Skip to content

Instantly share code, notes, and snippets.

@hzhu212
Last active May 12, 2021 12:24
Show Gist options
  • Save hzhu212/2bc5fb570c8d685a1c8da6abb8a4e2a8 to your computer and use it in GitHub Desktop.
Save hzhu212/2bc5fb570c8d685a1c8da6abb8a4e2a8 to your computer and use it in GitHub Desktop.
something about cache

a threading-safe cache decorator, cache result of function returns

from functools import wraps
import threading


class CallCache(object):
    def __init__(self):
        self.lock = threading.RLock()
        self.cache = {}

    def __call__(self, func):
        @wraps(func)
        def callee(*args, **kwargs):
            key = func.__name__
            with self.lock:
                if key in self.cache:
                    result = self.cache.get(key)
                else:
                    result = func(*args, **kwargs)
                    self.cache[key] = result
                return result

        return callee

cached = CallCache()

@cached
def foo():
    return 'foo'
    
@cached
def bar():
    return 'bar'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment