snippet python

Here I'm covering a few handy gems I found in the functools module.

@cache  # <---
def factorial(n):
    return n * factorial(n-1) if n else 1

>>> factorial(10)      # no previously cached result, makes 11 recursive calls
3628800
>>> factorial(5)       # just looks up cached value result
120
>>> factorial(12)      # makes two new recursive calls, the other 10 are cached
479001600

This is an alternative to a combination of @cache + @property

class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)

* @property runs the method code every time it is called.

https://www.geeksforgeeks.org/python-functools-cached_property/

Used in decorator functions, to have the returned wrapped function inherit attribites such as __doc__ fro mthe