A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/functools-module-in-python/ below:

Functools module in Python - GeeksforGeeks

Functools module in Python

Last Updated : 02 Aug, 2025

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.

  1. Provides higher-order functions and decorators that simplify functional programming tasks.
  2. Enables memoization using lru_cache() to speed up repeated function calls.
  3. Offers tools like partial() to fix certain arguments of a function and create simpler versions.
  4. Includes decorators like @total_ordering to reduce boilerplate when implementing rich comparisons.
  5. Helps write cleaner, more efficient and reusable code with minimal redundancy.
1. Partial class

The partial class 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)

Parameter:

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:

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)

Parameter:

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)

Explanation:

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:

cmp_to_key(func)

Parameter: func a function that compares two values and returns -1, 0, or 1.

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

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

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

Explanation:

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, iterable[, initializer])

Parameter:

Example: 

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

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

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

Output
Sum of list1 : 26
Maximum of list2 : xyz

Explanation:

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.

Syntax:

@total_ordering

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:

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)

Parameter:

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:

7. wraps

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

Syntax:

@wraps(wrapped, assigned, updated)

Parameter:

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:

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)

Parameter:

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:

9. singledispatch

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

Syntax:

@singledispatch

Example: 

Python
from functools import singledispatch

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

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

fun('GeeksforGeeks')  
fun(10)               

Explanation:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4