属性缓存
property-caching的Python项目详细描述
属性的缓存版本
由yola的人编写和使用来支持我们的free website builder。
概述
- cached_property-将修饰方法的结果存储在 装饰物 (在_cached_properties属性中)
- class_cached_property-将修饰方法的结果存储在 装饰物的类别 (在_class_cached_properties属性中)。所有实例将共享 缓存值。
- clear_property_cache-删除缓存值(对对象有效 仅缓存属性)
- set_property_cache-显式设置属性缓存(适用于 仅对象缓存属性)
- is_property_cached-允许检查属性是否已缓存 或不(仅适用于对象缓存属性)
用法
fromproperty_cachingimport(cached_property,class_cached_property,clear_property_cache,set_property_cache,truthy_cached_property)classDummy:@cached_propertydeffoo(self):returnself.service.expensive_operation()@truthy_cached_propertydefbar(self):# this value will only be cached if it doesn't evaluate to false:returnself.service.expensive_operation2()@class_cached_propertydefservice(self):returnexpensive_service_initialization()d=Dummy()d.foo# calculates result and stores it in d._cached_propertiesd.foo# uses cached valueclear_property_cache(d,'foo')# clears cache for property `foo`set_property_cache(d,'foo',42)# explicitly set cache for property `foo`d2=Dummy()d2.foo# re-calculates value of `foo` but uses cached service