Open In App

Functools module in Python

Last Updated : 02 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The functools module offers a collection of tools that simplify working with functions and callable objects. It includes utilities to modify, extend, or optimize functions without rewriting their core logic, helping you write cleaner and more efficient code.

Let's discuss them in detail.

1. Partial class

The partial class lets you fix certain arguments of a function and create a new function with fewer parameters. This is especially useful for creating specialized versions of functions without defining new ones from scratch.

Syntax:

partial(func, /, *args, **keywords)

Example: 

Python
from functools import partial

def power(a, b):
    return a ** b

pow2 = partial(power, b=2) 
pow4 = partial(power, b=4)  
power_of_5 = partial(power, 5) 

print(power(2, 3))    
print(pow2(4))       
print(pow4(3))       
print(power_of_5(2))  

print(pow2.func)     
print(pow2.keywords) 
print(power_of_5.args) 

Output
8
16
81
25
<function power at 0x7fb6fa23f100>
{'b': 2}
(5,)

Explanation:

  • partial.func: It returns the name of parent function along with hexadecimal address.
  • partial.args: It returns the positional arguments provided in partial function.
  • partial.keywords: It returns the keyword arguments provided in partial function.

2. Partialmethod Class

Partialmethod works like partial, but for class methods. It allows you to fix some method arguments when defining methods inside classes without making a new method manually.

Syntax:

partialmethod(func, *args, **keywords)

Example: 

Python
from functools import partialmethod

class Demo:
    def __init__(self):
        self.color = 'black'

    def _color(self, type):
        self.color = type

    set_red = partialmethod(_color, type='red')
    set_blue = partialmethod(_color, type='blue')
    set_green = partialmethod(_color, type='green')


obj = Demo()
print(obj.color)
obj.set_blue()
print(obj.color)

Output
black
blue

Explanation:

  • Defines methods with preset arguments inside classes.
  • Does not call methods itself; it's a method descriptor.
  • Helps reduce boilerplate when similar methods differ only by fixed arguments.

3. cmp_to_key

Cmp_to_key converts a comparison function into a key function. The comparison function must return 1, -1 and 0 for different conditions. It can be used in key functions such as sorted(), min(), max(). 

Syntax:

function(iterable, key=cmp_to_key(cmp_function))

Example: 

Python
from functools import cmp_to_key

def cmp_fun(a, b):
    if a[-1] > b[-1]:
        return 1
    elif a[-1] < b[-1]:
        return -1
    else:
        return 0

list1 = ['geeks', 'for', 'geeks']
sorted_list = sorted(list1, key=cmp_to_key(cmp_fun))
print('Sorted list:', sorted_list)

Output
Sorted list: ['for', 'geeks', 'geeks']

Explanation:

  • Converts comparison function to a key function.
  • Enables sorting by criteria like last character.
  • sorted() uses the key function to order items.

4. reduce

It applies a function of two arguments repeatedly on the elements of a sequence so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x^y, [1, 2, 3, 4]) calculates (((1^2)^3)^4). If the initial is present, it is placed first in the calculation, and the default result is when the sequence is empty. 

Syntax: 

reduce(function, sequence[, initial]) -> value

Example: 

Python
from functools import reduce
list1 = [2, 4, 7, 9, 1, 3]
sum_of_list1 = reduce(lambda a, b:a + b, list1)

list2 = ["abc", "xyz", "def"]
max_of_list2 = reduce(lambda a, b:a if a>b else b, list2)

print('Sum of list1 :', sum_of_list1)
print('Maximum of list2 :', max_of_list2)

Output
Sum of list1 : 26
Maximum of list2 : xyz

Explanation:

  • Combines elements pairwise using the given function.
  • Can take an optional initial value.
  • Useful for folding sequences into single results.

5. total_ordering

This class decorator automatically fills in missing comparison methods (__lt__, __gt__, etc.) based on the few you provide. It helps you write less code when implementing rich comparisons.

Example: 

Python
from functools import total_ordering

@total_ordering
class N:
    def __init__(self, value):
        self.value = value

    def __eq__(self, other):
        return self.value == other.value

    def __lt__(self, other):
        return self.value > other.value  # Inverted for demo

print('6 > 2:', N(6) > N(2))
print('3 < 1:', N(3) < N(1))
print('2 <= 7:', N(2) <= N(7))
print('9 >= 10:', N(9) >= N(10))
print('5 == 5:', N(5) == N(5))

Output
6 > 2: False
3 < 1: True
2 <= 7: False
9 >= 10: True
5 == 5: True

Explanation:

  • Automatically adds comparison methods based on your definitions.
  • Reduces errors and boilerplate in classes with complex comparisons.

6. update_wrapper

update_wrapper updates a wrapper function to copy attributes (__name__, __doc__, etc.) from the wrapped function. This improves debugging and introspection when wrapping functions.

Syntax:

update_wrapper(wrapper, wrapped[, assigned][, updated])

Example: 

Python
from functools import update_wrapper, partial

def power(a, b):
    '''a to the power b'''
    return a ** b

pow2 = partial(power, b=2)
pow2.__doc__ = 'a to the power 2'
pow2.__name__ = 'pow2'

print('Before update:')
print('Doc:', pow2.__doc__)
print('Name:', pow2.__name__)

update_wrapper(pow2, power)

print('After update:')
print('Doc:', pow2.__doc__)
print('Name:', pow2.__name__)

Output
Before update:
Doc: a to the power 2
Name: pow2
After update:
Doc: a to the power b
Name: power

Explanation:

  • Copies metadata from the original function to the wrapper.
  • Keeps function signatures and docs accurate after wrapping.

7. wraps

wraps is a decorator that applies update_wrapper automatically. It’s commonly used when writing decorators to preserve original function metadata.

Example: 

Python
from functools import wraps

def decorator(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        """Decorator's docstring"""
        return f(*args, **kwargs)
    print('Docstring:', decorated.__doc__)
    return decorated

@decorator
def f(x):
    """f's Docstring"""
    return x

print('Function name:', f.__name__)
print('Docstring:', f.__doc__)

Output
Docstring: f's Docstring
Function name: f
Docstring: f's Docstring

Explanation:

  • Simplifies copying metadata in decorators.
  • Keeps the decorated function’s name and docstring intact.

8. lru_cache

lru_cache caches recent function results to speed up repeated calls with the same arguments, improving performance at the cost of memory.

Syntax:

@lru_cache(maxsize=128, typed=False)

Example: 

Python
from functools import lru_cache

@lru_cache(maxsize=None)
def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n-1)

print([factorial(n) for n in range(7)])
print(factorial.cache_info())

Output
[1, 1, 2, 6, 24, 120, 720]
CacheInfo(hits=5, misses=7, maxsize=None, currsize=7)

Explanation:

  • Memoizes function calls for faster repeated access.
  • Cache info shows hits, misses, and size.

9. singledispatch

signedispatch turns a function into a generic function that dispatches calls to different implementations based on the type of the first argument.

Example: 

Python
from functools import singledispatch

@singledispatch
def fun(s):
    print(s)

@fun.register(int)
def _(s):
    print(s * 2)

fun('GeeksforGeeks')  
fun(10)               

Output
GeeksforGeeks
20

Explanation:

  • Enables type-based function overloading.
  • Different behavior for different argument types.

Next Article
Article Tags :
Practice Tags :

Similar Reads