Table of Contents

import functools

import functools is a Python import that provides functional programming tools: function caching, partial application, and wrapping functions with decorators.

Example

# Python
# description: cache function results, partial application
 
from functools import lru_cache, partial, wraps
 
# Cache function results (memoization)
@lru_cache(maxsize=128)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)
 
print(fibonacci(10))  # Fast due to caching
 
# Partial application - fix some arguments
def multiply(a, b):
    return a * b
 
double = partial(multiply, 2)
print(double(5))  # 10
 
# Decorator that preserves metadata
def timer(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper
 
@timer
def greet(name):
    return f"Hello, {name}"
 
print(greet("Alice"))

Common functions