Functools Higher-Order Functions

Advanced PythonFunctional ProgrammingFree Lesson

Advertisement

Introduction

Functools provides higher-order functions and operations on callable objects.

LRU Cache

from functools import lru_cache

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

# Clear cache
fibonacci.cache_clear()

# Cache info
print(fibonacci.cache_info())
# CacheInfo(hits=0, misses=60, ...)

Partial Functions

from functools import partial

def power(base, exponent):
    return base ** exponent

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

print(square(5))  # 25
print(cube(3))    # 27

Reducing Functions

from functools import reduce

# Reduce to single value
numbers = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x * y, numbers)
print(result)  # 120

Practice Problems

  1. Memoize recursive factorial
  2. Create partial function with positional args
  3. Use reduce for custom aggregations
  4. Implement caching decorator
  5. Create function composition with reduce

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement