About Caching Method Values
You can cache the value of a method so that it can be called more than once, but calculated just once:
class SomeClass(object):
def calc(self):
if not hasattr(self, "_calc_cache"):
self._calc_cache = ... # some heavy calculations
return self._calc_cache
Another option – use @lru_cache
decorator:
from functools import lru_cache
class SomeClass(object):
@lru_cache(maxsize=None)
def calc(self):
return ...
Or just use the @cache
decorator since Python 3.9:
from functools import cache
class SomeClass(object):
@cache
def calc(self):
return ...
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django App for You
Django GDPR Cookie Consent app
For Django websites that use cookies.
Django App for You