Skip to content

Commit

Permalink
#2817: Adds a mutable property cache utility
Browse files Browse the repository at this point in the history
  • Loading branch information
mauromsl committed Sep 13, 2022
1 parent 666eb32 commit 704f3b8
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/utils/function_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from hashlib import sha1

from django.core.cache import cache as django_cache
from django.utils.functional import cached_property


def cache(seconds=900):
Expand All @@ -24,3 +25,25 @@ def y(*args, **kwargs):
return result
return y
return do_cache


class mutable_cached_property(cached_property):
""" Expands django's cached property to allow property mutation
A property mutation (__set__) will clear the previously cached value
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fsetter = None

def __set__(self, obj, value):
if self.fsetter is None:
raise AttributeError(f"property '{self.name}' has no setter")
self.fsetter(obj, value)
obj.__dict__[self.name] = self.func(obj)

def setter(self, fsetter):
prop = type(self)(self.func, self.name)
prop.setter = fsetter
return prop

0 comments on commit 704f3b8

Please # to comment.