Functools module in Python
Last Updated :
02 Jun, 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.
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)
Output8
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)
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)
OutputSorted 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)
OutputSum 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))
Output6 > 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__)
OutputBefore 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__)
OutputDocstring: 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)
Explanation:
- Enables type-based function overloading.
- Different behavior for different argument types.
Similar Reads
Python Modules
Python Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work.In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we c
7 min read
Python Arrays
Lists in Python are the most flexible and commonly used data structure for sequential storage. They are similar to arrays in other languages but with several key differences:Dynamic Typing: Python lists can hold elements of different types in the same list. We can have an integer, a string and even
9 min read
asyncio in Python
Asyncio is a Python library that is used for concurrent programming, including the use of async iterator in Python. It is not multi-threading or multi-processing. Asyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web servers, databa
4 min read
Calendar in Python
Python has a built-in Python Calendar module to work with date-related tasks. Using the module, we can display a particular month as well as the whole calendar of a year. In this article, we will see how to print a calendar month and year using Python. Calendar in Python ExampleInput: yy = 2023 mm =
2 min read
Python Collections Module
The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them. Some of the built-in containers are Tuple, List, Dictionary, etc. In this article, we will
12 min read
Working with csv files in Python
Python is one of the important fields for data scientists and many programmers to handle a variety of data. CSV (Comma-Separated Values) is one of the prevalent and accessible file formats for storing and exchanging tabular data. In article explains What is CSV. Working with CSV files in Python, Rea
10 min read
Python datetime module
In Python, date and time are not data types of their own, but a module named DateTime in Python can be imported to work with the date as well as time. Python Datetime module comes built into Python, so there is no need to install it externally. In this article, we will explore How DateTime in Python
14 min read
Functools module in Python
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 cl
5 min read
hashlib module in Python
A Cryptographic hash function is a function that takes in input data and produces a statistically unique output, which is unique to that particular set of data. The hash is a fixed-length byte stream used to ensure the integrity of the data. In this article, you will learn to use the hashlib module
5 min read
Heap queue or heapq in Python
A heap queue or priority queue is a data structure that allows us to quickly access the smallest (min-heap) or largest (max-heap) element. A heap is typically implemented as a binary tree, where each parent node's value is smaller (for a min-heap) or larger (for a max-heap) than its children. Howeve
7 min read