我正在使用functools.cached_property
来存储一个长寿命会话对象,如下所示:
class Client:
@cached_property
def session(self):
return service.login(...)
我只想在非常特定的情况下使缓存无效,而不放弃cached_property
的便利性和清晰度。我怎样才能做到这一点?
functools.cached_property
使用与存储常规实例属性(self.attr = ...
(相同的位置:对象的.__dict__
!因此,您的案例的无效方法看起来像:
class Client:
@cached_property
def session(self):
return service.login(...)
def logout(self):
self.__dict__.pop('session', None)
如果你想使一个对象的所有cached_property
无效,你可以这样做:
def invalidate_cached_properties(obj):
cls = type(obj)
cached = {
attr
for attr in list(self.__dict__.keys())
if (descriptor := getattr(cls, attr, None))
if isinstance(descriptor, cached_property)
}
for attr in cached:
del obj.__dict__[attr]