What is the use of the Python functools module?

What is the use of the Python functools module?

a) It provides higher-order functions that act on or return other functions
b) It is used to work with dates and times
c) It provides tools for creating and managing iterators
d) It helps in mathematical computations

Answer:

a) It provides higher-order functions that act on or return other functions

Explanation:

The functools module in Python provides higher-order functions that work with or return other functions. This includes tools for function manipulation, such as lru_cache, partial, and wraps, which are used to enhance and extend the behavior of functions.

from functools import lru_cache

@lru_cache(maxsize=32)
def factorial(n):
if n == 0:
    return 1
return n * factorial(n-1)

print(factorial(5))  # Output: 120

In this example, the lru_cache decorator is used to cache the results of the factorial function, improving performance by avoiding redundant calculations.

The functools module is particularly valuable in functional programming, where functions are treated as first-class citizens, and in scenarios requiring optimization and function manipulation.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top