Python partial functions using functools
Recommended by 0 users
Despite being a fully object oriented language and not an inherently functional language, Python has its unique set of functional programming tools. Partial functions in Python can be created in style with the help of functools library. Partial functions allow one to derive a function with x parameters to a function with fewer parameters and fixed values set for the more limited function.
functools module is for higher-order functions: functions that act on or return other functions. This module provides tools for working with functions and other callable objects, to adapt or extend them for new purposes without completely rewriting them.In general, any callable object can be treated as a function for the purposes of this module.
Though Python is not a functional language, but this particular field helps coders to write their own code in a functional style and one such feature of functools library is to create partial functions. In other words functools module is for higher order functions where functions can either act or return on other functions. In order to use partial functions the following import is required:
>>> from functools import partial
Partial function helps you to derive a function with x parameters to a function with fewer parameters. In a partial function, one constant value argument can be bound to a definite function to create a new function that will take only the rest of the operations. Amongst all calls, the bound input will remain the same. To understand its application in detail, have a glimpse at the following example:
The primary tool supplied by the functools module is the class partial, which can be used to “wrap” a callable object with default arguments. Partial objects are similar to function objects with slight differences. Partial function application makes it easier to write and maintain the code.
What functools.partial does is:
- Makes a new version of a function with one or more arguments already filled in.
- New version of a function documents itself.
Now, have a look at another example of how to find a cube of a number with the help of partial functions:
Enroll for Instructor Led Live Python Training