函数执行结果缓存
2018-10-13 本文已影响0人
不_一
# -*- coding: utf-8 -*-
from time import time
class cached_property(object):
def __init__(self, ttl=None):
ttl_or_func = ttl
self.ttl = None
if callable(ttl_or_func):
self.prepare_func(ttl_or_func)
else:
self.ttl = ttl_or_func
def prepare_func(self, func, doc=None):
"""Prepare to cache object method."""
self.func = func
self.__doc__ = doc or func.__doc__
self.__name__ = func.__name__
self.__module__ = func.__module__
def __call__(self, func, doc=None):
self.prepare_func(func, doc)
return self
def __get__(self, obj, cls):
if obj is None:
return self
now = time()
try:
value, last_update = obj._cache[self.__name__]
if self.ttl and self.ttl > 0 and now - last_update > self.ttl:
raise AttributeError
except (KeyError, AttributeError):
value = self.func(obj)
try:
cache = obj._cache
except AttributeError:
cache = obj._cache = {}
cache[self.__name__] = (value, now)
return value
class Foo(object):
def __init__(self):
pass
@cached_property
def pp(self):
return 'hello'
def world(self):
return 'world'
PP = cached_property(world)
print(PP)
print(world)
#
# print(Foo())
# print(Foo().pp)
print(Foo().PP) # 传入self