Python’s amazing functools module
By: Aditya Dhanraj Tiwari
Tags: Python Programming, Python3, Coding, Python, Programming

Python’s amazing functools module

Kill the messier code with functools elegancy

downloaded from wallpaper cave

functools.partial

Partial is a higher order function which allows the partial application of a function. Suppose there is a function with lots of arguments but you need to change only one or two argument every time you use that function, Partial function comes to the rescue. Using Partial function, you can fix any argument value the number of arguments of a function thus removing the necessity of creating another one. What you get as a result is an elegant and easy to read code.

Let’s see it in action →

The logger function above takes 2 arguments — log_level and message.

Problem Statement — The requirement is clearly just to log all the messages at same ‘DEBUG’ level, but unfortunately with every function call to logger method we are forced to pass the argument log_level with value ‘DEBUG’.

Solution — Using partial function we fixed the value of log_level to ‘DEBUG’ and created a much more convenient function debug_logger which now accepts message as the only argument and returns the same result.

functools.lru_cache

The function that we are going to discuss now is undoubtedly one of my favorites. Just imagine, you can solve almost 40–50% Dynamic programming question with the help of “lru_cache” decorator.

LRU stands for Least Recently Used, it saves the result of last executed function in memory and when it have to again execute the function, first it will check in cache, if found it will return the result otherwise it will go on to execute the function.

“lru_cache” can save us a lot of time when we need to perform computationally expensive or I/O bound operations through a function.

Let’s understand the above concept with an example →

Just applying the “lru_cache” decorator over a function will make the above algorithm execute crazy fast, try this approach the next time you are solving a problem and witness it’s true power yourself.

functools.singledispatch

“singledispatch” implementation lets you achieve function overloading. It converts your function into a generic function which can have different behavior depending on the type of first argument.

Use “singledispatch” decorator over the default implementation and then simply add “@<functionname>.register(<type>)” over the functions that you need to overload.

Let’s see the code for implementation of above concept in action →

If not for “singledispatch”, multiple if else conditions would be required, just to implement the above piece of code; and every time a requirement to handle a new type arises in future, we would be forced to make changes to the doubleTheValue function, resulting in violation of the Open close principle.

functools.reduce

Reduce is again a higher order function which is primarily used to accumulate data while iterating over a passed sequence →

reduce(function, sequence, start)

Working of reduce function →

1. In first iteration, the function provided is applied to the first element of a sequence and the start value, and the result is then returned to next iteration.

2. In second iteration, the same function is applied on the previously calculated result and the next element of the sequence, the result is then updated with the newly calculated value.

3. In all subsequent iterations, Step 2 is executed repeatedly until the sequence is exhausted, and the final result is then returned.

Reduce always returns a single value.

Let’s see reduce in action →

Conclusion

In this article we have learned about functools module and we saw how it can make our code more readable, elegant and fast. I hope you will feel more comfortable using functools module after you have read this article and familiarized yourself with it’s functions.

Good Luck, Happy Coding !! 😊