可扩展的备忘录集合和装饰器
cachetools的Python项目详细描述
本模块提供各种备忘录集合和装饰器, 包括python 3标准库的变体@lru_cache 函数装饰器。
fromcachetoolsimportcached,LRUCache,TTLCache# speed up calculating Fibonacci numbers with dynamic programming@cached(cache={})deffib(n):returnnifn<2elsefib(n-1)+fib(n-2)# cache least recently used Python Enhancement Proposals@cached(cache=LRUCache(maxsize=32))defget_pep(num):url='http://www.python.org/dev/peps/pep-%04d/'%numwithurllib.request.urlopen(url)ass:returns.read()# cache weather data for no longer than ten minutes@cached(cache=TTLCache(maxsize=1024,ttl=600))defget_weather(place):returnowm.weather_at_place(place).get_weather()
在这个模块中,cache是 固定最大尺寸。当缓存已满时,即通过添加另一个 项目缓存将超过其最大大小,缓存必须选择 根据合适的cache algorithm丢弃哪些项。在 一般来说,缓存的大小是其项的总大小,而项的 大小是其值的属性或函数,例如 sys.getsizeof(value)。对于每个 项计数为1,缓存的大小等于其 项目,或len(cache)。
基于不同缓存算法的多个缓存类是 实现和修饰程序,以便轻松记住函数和方法 电话也有。
有关详细信息,请参阅联机documentation。
安装
使用pip安装cachetools:
pip install cachetools