File size: 999 Bytes
f31fe4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# coding: utf-8

"""Simple callcache implementation.

The CallCache does not using lock because we assume that all function result to be cached will be the same in multiple
calls, and do not take any heavy costs, so the function which to be cached may be called multiple times in multi thread
scenario.
"""

from __future__ import absolute_import, division, print_function, unicode_literals

import threading
from functools import wraps

__author__ = 'anlong <anlong@bytedance.com>'


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

    def __call__(self, func):
        @wraps(func)
        def callee():  # notice: do not support functions with arguments by design, for prevent cache flood DoS.
            key = func.__name__
            if key in self.cache:
                result = self.cache.get(key)
            else:
                result = func()
                self.cache[key] = result
            return result
        return callee


callcache = CallCache()