For @cached_property
decorated methods, is there a built-in way to iterate through all of these attributes? My use case is that I’d like to clear all cached properties with the del
operator without bookkeeping for them manually in something like a list.
Here’s a canned example. __init__
could do something fancy like load data from a file that needs to be reloaded later, which means all cached properties would need to be recomputed.
class MyData: def __init__(self): self.a = 0 self.b = 0 @cached_property def sum(self): return self.a + self.b def reload(self): # Is there anything keeping track of cached properties? for prop in self.__something__.cached_properties: del prop
Advertisement
Answer
Caching is separate for each attribute and there doesn’t seem to be any built-in to find them as a list.
One approach would be to iterate through all of the attributes of an instance, and determine which are cached properties based on the fact that the attribute method in the class object will be an instance of cached_property
.
Something like this would work:
def reload(self): cls = self.__class__ attrs = [a for a in dir(self) if isinstance(getattr(cls, a, cls), cached_property)] for a in attrs: delattr(self, a)
(the third argument to getattr()
is to return a default value in case the instance has an attribute the class doesn’t, and not generate an error)