二哥啊

导航

 
from functools import wraps
import inspect
import time
import datetime

def m_cache(fn):
local_cache = {}
def wrapper(*args, **kwargs):
# local_cache有没有过期的key
expire_keys = []
for k,(_,ts) in local_cache.items():
if datetime.datetime.now().timestamp()- ts >5 :
expire_keys.append(k)
for k in expire_keys:
local_cache.pop(k)


key_dict = {} #sorted
sig = inspect.signature(fn)
params = sig.parameters #有序字典

param_list = list(params.keys())
# 位置参数
for i,v in enumerate(args):

k = param_list[i]
key_dict[k] = v
# 关键字
# for k,v in kwargs.items():
# key_dict[k] = v
key_dict.update(kwargs)

# 缺省值
for k in params.keys():
if k not in key_dict.keys():
key_dict[k] = params[k].default

key = tuple(sorted(key_dict.items()))
if key not in local_cache.keys():
ret = fn(*args, **kwargs)
local_cache[key] = (ret,datetime.datetime.now().timestamp())
return local_cache[key ]
return wrapper

@m_cache
def add(x,y=5):
time.sleep(3)
ret = x+y
return ret


if __name__ == "__main__":
print(add(4))
print(add(4,5))
print(add(4,y=5))
print(add(y=5,x=4))
posted on 2019-09-03 20:45  二哥啊  阅读(174)  评论(0编辑  收藏  举报