Mastering Python's functools Module 🧰

Function tools icon

Mastering Python's functools Module 🧰

The functools module provides powerful tools for functional programming, helping you write efficient and reusable Python code. Let’s dive into its key functionalities with clear examples.

1. lru_cache: Speed Up Functions by Caching Results

from functools import lru_cache

@lru_cache(maxsize=None)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(30))  # Quick result due to caching

2. partial: Fix Arguments of a Function

from functools import partial

def multiply(x, y):
    return x * y

double = partial(multiply, 2)
print(double(5))  # 10

3. cmp_to_key: Custom Sorting with a Comparison Function

from functools import cmp_to_key

def compare(a, b):
    return b - a  # Descending order

numbers = [5, 2, 9, 1]
sorted_numbers = sorted(numbers, key=cmp_to_key(compare))
print(sorted_numbers)  # [9, 5, 2, 1]

4. wraps: Preserve Original Metadata in Decorators

from functools import wraps

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

@my_decorator
def greet(name):
    """Greets a person by name."""
    print(f"Hello, {name}")

print(greet.__name__)  # greet
print(greet.__doc__)   # Greets a person by name.

Summary

  • lru_cache dramatically speeds up recursive functions by caching their results.
  • partial creates new functions by pre-filling some arguments of existing functions.
  • cmp_to_key enables sorting lists using custom comparison functions.
  • wraps maintains the original metadata of functions when using decorators.

Comments

Popular posts from this blog

Mastering Python Generators and yield: Efficient Iteration Explained

Mastering Python Sets: Remove Duplicates and Do More

Python Logging Module: Basics and Best Practices 📝