Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Python is an interpreted and high-level programming language. It provides various modules to write efficient code in it. There is a module that is used in functional programming, i.e. functools. So, functools module provides various tools to use functions, decorators, etc.
In this blog, we will discuss about Python functools module. We will discuss why and how to use it. We will also explain its classes and functions. Before moving forward, let us understand what the Python functools module is.
So, let's get started!!
A Brief about Python Functools Module
A Python functools module is a module that comes under the standard library of Python. This module helps programmers to manipulate the functions and make them more advanced so that they can use them later in their applications. It provides various high-order functions such as reduce(), wraps(), etc.
We will discuss these functions later in this blog.
Python functools module is used to enhance the capabilities of functions and make them more reusable. This module also provides tools like partial functions and other utility functions to alter the behavior of normal functions.
Now, you might be wondering how to use functools module.
How to Use Python Functools Module?
When it comes to how to use functools module, then we just need to follow a simple step. We need to import this module into our program, and then we can use it anywhere. To start using functools module, we need to write a simple import statement:
import functools
Classes in Python Functools Module
There are two classes in the functools module:
partial Class
The partial class in the functools module allows us to create a new function with some of the original function's arguments that are already set. This can be helpful when you want to simplify function calls by fixing specific arguments.
Let us look at the example of the partial class.
Python
Python
from functools import partial as partialClass
# This is our original function
def power(baseNum, exponentNum):
return baseNum ** exponentNum
# Invoking the original function
res = power(2, 3)
print("The result of original function is",res)
print("After applying partialClass...")
# Creating a new function with fixed base as 3
cube = partialClass(power, 3)
# Calculating the cube of a number using our new function
ans = cube(3)
print("Cube of the number is",ans)
You can also try this code with Online Python Compiler
In this example, we are building an image-processing application. So, we have created an ImageProcessor class. This class represents an image. As we know, the image can have multiple filters, such as grayscale, sepia, and invert. So, we have created methods to apply these filters. We have fixed the filter type for each method using partialmethod class.
Functions in Python Functools Module
There are several functions that are provided by the functools module. Let us discuss a few of them:
reduce() Function
The reduce() function in the functools module is used to apply a binary function cumulatively to the items of an iterable from left to right. Then it produces a single reduced result. We can see the steps as well to understand the reduce() function’s working:
Let us discuss it with the help of an example.
Python
Python
from functools import reduce
# Defining a multiply function
def multiply(x, y):
return x * y
# Calculating the product of all elements in a list using reduce
num = [4, 2, 3, 6, 5]
ans = reduce(multiply, num)
print("The multiplication of the numbers in the list is", ans)
You can also try this code with Online Python Compiler
The multiplication of the numbers in the list is 720
lru_cache() Function
The lru_cache() function is used for memoization. It helps to cache the results of expensive function calls to improve the performance.
Let us discuss it with the help of an example.
Python
Python
from functools import lru_cache
# Finding Fibonacci using memoization
@lru_cache(maxsize=None)
def fib(n):
if n <= 1:
return n
else:
return fib(n-1) + fib(n-2)
# Calculating the Fibonacci
ans = fib(9)
print("The 9th Fibonacci is",ans)
You can also try this code with Online Python Compiler
In this example, we have used memoization to find the 9th Fibonacci number efficiently. The @lru_cache decorator from the functools module is applied to the Fibonacci function. It has enabled the memoization for this recursive function. Using memoization with lru_cache effectively turned the recursive Fibonacci function into a dynamic programming solution. That’s why the results of subproblems are stored and reused when needed. This is how lru_cache has improved the performance of the recursive Fibonacci function.
wraps() Function
The wraps() function is a decorator. It preserves the metadata of the original function when creating a new decorator. When we use the wraps decorator, it ensures that when we create a new decorator, it doesn't lose the important properties of the original function. In simple words, it acts like a wrapper around the new decorator. This makes sure that it looks and behaves like the original function.
Let us discuss it with the help of an example.
Python
Python
from functools import wraps
def exampleDeco(func):
@wraps(func)
def wrapper(*args, **kwargs):
# Print a message before the wrapped function is executed
print("Loading…. before the function is called.")
# Call the original function and store its result
ans = func(*args, **kwargs)
# Print a message after the wrapped function is executed
print("Loading ended…. after the function is called.")
# Return the answer of the original function
return ans
# Return the decorated wrapper function
return wrapper
@exampleDeco
def greeting():
print("Hello! Ninjas")
# Calling the decorated function
greeting()
You can also try this code with Online Python Compiler
Loading…. before the function is called.
Hello! Ninjas
Loading ended…. after the function is called.
Explanation
In this example, we have defined a decorator exampleDeco. It uses the wraps() function from the functools module. Then we have applied the exampleDeco decorator to the greeting() function. When we call the decorated greeting() function, the decorator prints loading messages before and after the original function is executed.
Frequently Asked Questions
What do you mean by functional programming in Python?
Functional programming treats computation as the evaluation of mathematical functions. It promotes code reusability, modularity, and ease of debugging.
Can we use the functools module with custom decorators?
Yes, we can use the functools module with custom decorators. We can apply the wraps decorator.
When should we use the lru_cache decorator?
We can use the lru_cache decorator when we have a computationally expensive function that is called with the same arguments repeatedly. Memoization provided by this decorator can significantly improve performance by caching results.
How does the reduce() function differ from map() and filter()?
The reduce() function aggregates the elements of an iterable using a binary function, Then it produces a single reduced result. The map() and filter() transform and filter elements, respectively, in an iterable, producing a new iterable.
Conclusion
In this blog, we have discussed about Python Functools module. We have covered classes and functions that come with functools module. We have also discussed several examples. If you want to learn more about the Python modules, then you can check out our blogs:
We hope this blog helps you to get knowledge about the Python Functools module. You can refer to our guided paths on the Codestudio platform. You can also consider our paid courses such asDSA in Python to give your career an edge over others!