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:

1
2
3
4
5
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:

1
2
3
4
5
6
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:

1
2
3
4
5
6
from functools import cache

class SomeClass(object):
    @cache
    def calc(self):
        return ...

Tips and Tricks Programming Python 3