python 基础——实现一个带缓存功能的函数

时间:2023-03-09 08:39:59
python 基础——实现一个带缓存功能的函数
from functools import wraps

def cache(func):
data = {}
@wraps(func)
def wrapper(*args):
if args in data:
print "in cache"
return data[args]
else:
print "not in cache"
res = func(*args)
data[args] = res
return res
return wrapper @cache
def post_data(args):
return args post_data(123) # not in cache
post_data(123) # in cache
post_data(1235) # not in cache