🛠️

How to Use functools in Python

PythonAdvanced

Higher-order functions and decorators.

Code Example

Python
from functools import reduce, partial, lru_cache

# Reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(f"Product: {product}")

sum_all = reduce(lambda x, y: x + y, numbers)
print(f"Sum: {sum_all}")

# Partial functions
def power(base, exponent):
    return base ** exponent

square = partial(power, exponent=2)
cube = partial(power, exponent=3)

print(f"\nSquare of 5: {square(5)}")
print(f"Cube of 5: {cube(5)}")

# LRU Cache
@lru_cache(maxsize=32)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

print(f"\nFibonacci(10): {fibonacci(10)}")
print(f"Cache info: {fibonacci.cache_info()}")

# Wraps decorator
from functools import wraps

def my_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        """Wrapper function"""
        return func(*args, **kwargs)
    return wrapper

@my_decorator
def example():
    """Example function"""
    pass

print(f"\nName: {example.__name__}")
print(f"Doc: {example.__doc__}")

# Total ordering
from functools import total_ordering

@total_ordering
class Student:
    def __init__(self, grade):
        self.grade = grade
    
    def __eq__(self, other):
        return self.grade == other.grade
    
    def __lt__(self, other):
        return self.grade < other.grade

s1 = Student(85)
s2 = Student(90)
print(f"\ns1 < s2: {s1 < s2}")
print(f"s1 <= s2: {s1 <= s2}")

Explanation

functools provides higher-order functions. reduce() combines items, partial() creates specialized functions, lru_cache() memoizes, wraps() preserves metadata.

Related Tutorials