Functools — Higher-order functions and operations on callable objects in Python

PythonServer Side ProgrammingProgramming

Function in Python is said to be of higher order. It means that it can be passed as argument to another function and/or can return other function as well. The functools module provides important utilities for such higher order functions.

partial() function

This function returns a callable 'partial' object. The object itself behaves like a function. The partial() function receives another function as argument and freezes some portion of a function’s arguments resulting in a new object with a simplified signature.

The built-in int() function converts a number to a decimal integer. Default signature of int() is

int(x, base = 10)

The partial() function can be used to create a callable that behaves like the int() function where the base argument defaults to two.

>>> import functools
>>> binint = functools.partial(int, base = 2)
>>> binint('1001')
9

In following example, a user defined function myfunction() is used as argument to a partial function by setting default value on one of the arguments of original function.

>>> def myfunction(a,b):
return a*b

>>> partfunction = functools.partial(myfunction,b = 10)
>>> partfunction(10)
100

partialmethod()

This function returns a new partialmethod descriptor which behaves like partial except that it is designed to be used as a method definition rather than being directly callable.

Cmp_to_key() function

Python 2.x had cmp() function for comparison of two objects. Python 3 has deprecated it. The functools module provides cmp_to_key() function by which comparison of objects of user defined classes can be performed

from functools import cmp_to_key

class test:
def __init__(self,x):
self.x = x
def __str__(self):
return str(self.x)
def cmpr( a,b):
if a.x> = b.x: return True
if a.x<b.x: return False
mykey = cmp_to_key(cmpr)

reduce() function

The reduce() function receives two arguments, a function and an iterable. However, it returns a single value. The argument function is applied cumulatively two arguments in the list from left to right. Result of the function in first call becomes first argument and third item in list becomes second. This is repeated till list is exhausted.

In the example below, mult() function is defined to return product of two numbers. This function is used in reduce() function along with a range of numbers between 1 to 10. Output is a factorial value of 10.

import functools
def mult(x,y):
return x*y

num = functools.reduce(mult, range(1,11))
print ('factorial of 10: ',num)

Output

factorial of 10: 3628800
raja
Published on 16-Apr-2019 12:06:08
Advertisements