Functools

Functools has higher order functions that may be useful when writing code in a functional style.

Cache

from functools import cache

@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

Reduce

Even though map is a freestanding function, reduce is not.

from functools import reduce

reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) # 15

LRU Cache

You can LRU cache some too:

from functools import lru_cache

@lru_cache
def count_vowels(sentence):
    sentence = sentence.casefold()
    return sum(sentence.count(vowel) for vowel in 'aeiou')

Generate Total Ordering

Generate the spaceship operator by supplying an __eq__() operator and one of the four comparisons: __lt__(), __le__(), __gt__(), or __ge__()

@total_ordering
class Student:
    def _is_valid_operand(self, other):
        return (hasattr(other, "lastname") and
                hasattr(other, "firstname"))
    def __eq__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) ==
                (other.lastname.lower(), other.firstname.lower()))
    def __lt__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) <
                (other.lastname.lower(), other.firstname.lower()))