WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Python · Advanced · question 47 of 100

What are the key features of Python’s functools module, and how can they be used to optimize code?

📕 Buy this interview preparation book: 100 Python questions & answers — PDF + EPUB for $5

The functools module in Python provides several functions that help with higher-order functions, such as caching, partial function application, and others. Here are some of the key features of the functools module:

partial(): The partial() function can be used to create a new function with some of the arguments of an existing function already filled in. This can be useful when you want to create a new function that is a variation of an existing one. Here is an example:

    from functools import partial
    
    def multiply(x, y):
        return x * y
    
    double = partial(multiply, y=2)
    
    print(double(5)) # Output: 10

In this example, we use partial() to create a new function called double() that multiplies its argument by 2. We do this by passing the multiply() function and the value 2 as arguments to partial(). The resulting function is assigned to the variable double, which we can then use to multiply numbers by 2.

lru_cache(): The lru_cache() function can be used to cache the results of a function to improve performance. When you call a function that has been cached with lru_cache(), the result is returned immediately without the function being executed again. Here is an example:

    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(n) for n in range(10)])

In this example, we define a function called fibonacci() that calculates the nth Fibonacci number recursively. We use the lru_cache() decorator to cache the results of the function, so that the function is only called once for each value of n. We then print out the first 10 Fibonacci numbers using a list comprehension.

reduce(): The reduce() function can be used to apply a function to the elements of a list to reduce them to a single value. Here is an example:

    from functools import reduce
    
    numbers = [1, 2, 3, 4, 5]
    product = reduce(lambda x, y: x * y, numbers)
    
    print(product) # Output: 120

In this example, we use reduce() to multiply all the numbers in a list together. We pass a lambda function that takes two arguments and returns their product as the first argument to reduce(). reduce() applies the lambda function to the elements of the list in a cumulative way, resulting in the product of all the numbers.

wraps(): The wraps() function is a decorator that can be used to preserve the metadata of a function when it is wrapped by another function. Here is an example:

    from functools import wraps
    
    def my_decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            print("Calling function")
            return func(*args, **kwargs)
        return wrapper
    
    @my_decorator
    def my_function():
        """This is a docstring"""
        pass
    
    print(my_function.__name__) # Output: my_function
    print(my_function.__doc__) # Output: This is a docstring

In this example, we define a decorator called my_decorator() that adds some logging around the function it decorates. We use wraps() to ensure that the metadata of the original function is preserved when it is wrapped. We then apply the my_decorator() decorator to a function called my_function() and print out its name and docstring to verify that the metadata has been preserved.

Overall, the functools module provides several useful tools for optimizing and structuring code in Python.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Python interview — then scores it.
📞 Practice Python — free 15 min
📕 Buy this interview preparation book: 100 Python questions & answers — PDF + EPUB for $5

All 100 Python questions · All topics