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
def calc(self):
    if not hasattr(self, "_calc_cache"):
        self._calc_cache = ... # some heavy calculations
    return self._calc_cache

Tips and Tricks Programming Python 3.6 Python 2.7