需要的时候擦干净
xcache的Python项目详细描述
它类似于lru_caches,但可以自动清除或通过上下文管理器清除。
为什么?
There are only two hard things in Computer Science: cache invalidation and naming things.
–菲尔卡尔顿
所以,缓存是相当容易的,但是它们的失效是很难纠正的。
使用哪种类型的缓存?
默认的实现是stdlib的lru_缓存,但您可以自己放入。
怎么做?
python的特点是垃圾收集aka。自动内存管理。让我们利用它:
fromxcacheimportcache_genrequest_cache=cache_gen(lambda:request)# default cache_impl=lru_cache
在这里,我们定义了自己的缓存,需要全局请求来使缓存失效。 只要request被垃圾回收,缓存的数据就会被释放。
@request_cache()deffib(n):returnfib(n-1)+fib(n-2)ifn>1else1
在这里,我们将看到如何装饰函数,使其像lru_u缓存一样工作。
现在,让我们看看它是如何工作的:
classRequest():passrequest=Request()print(fib(10))print(fib(20))print(fib.cache_info())# fib cache contains 2 itemsrequest=Request()# invalidates all cachesprint(fib.cache_info())# fib cache contains 0 itemsprint(fib(10))print(fib(20))
上下文管理器,用于对缓存失效进行更多控制
如果需要更多的控制,则需要上下文管理器clean_caches:
fromxcacheimportcached,clean_caches@cached()deffib(n):returnfib(n-1)+fib(n-2)ifn>1else1withclean_caches():print(fib(10))print(fib(20))print(fib.cache_info())# fib cache contains 2 itemsprint(fib.cache_info())# fib cache contains 0 items
甚至可以指定缓存应附加到的对象:
@cached()deffib(n):returnfib(n-1)+fib(n-2)ifn>1else1withclean_caches(Request())asrequest:print(fib(10))print(fib(20))print(fib.cache_info())# fib cache contains 2 itemsprint(fib.cache_info())# fib cache contains 0 items
这些上下文管理器可以嵌套吗?
当然。在每个上下文的每个入口和出口,所有相关的缓存都被清空。
结论
良好
- 缓存失效操作简单
- 通过垃圾收集工作
- 通过上下文管理器工作
- 与python2和python3一起工作
坏
- 未知;-)
创意总是受欢迎的。:-)