Functools module in Python
Last Updated :
14 Sep, 2022
Functools module is for higher-order functions that work on other functions. It provides functions for working with other functions and callable objects to use or extend them without completely rewriting them. This module has two classes – partial and partialmethod.
Partial class
A partial function is an original function for particular argument values. They can be created in Python by using “partial” from the functools library. The __name__ and __doc__ attributes are to be created by the programmer as they are not created automatically. Objects created by partial() have three read-only attributes: Syntax:
partial(func, /, *args, **keywords)
- 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.
Example:
Python3
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('Function used in partial function pow2 :', pow2.func)
print('Default keywords for pow2 :', pow2.keywords)
print('Default arguments for power_of_5 :', power_of_5.args)
|
Output
8
16
81
25
Function used in partial function pow2 : <function power at 0x7f8fcae38320>
Default keywords for pow2 : {'b': 2}
Default arguments for power_of_5 : (5,)
Partialmethod class
It is a method definition of an already defined function for specific arguments like a partial function. However, it is not callable but is only a method descriptor. It returns a new partialmethod descriptor.
Syntax:
partialmethod(func, *args, **keywords)
Example:
Python3
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
Functions
Cmp_to_key It 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:
Python3
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']
l = sorted(list1, key = cmp_to_key(cmp_fun))
print('sorted list :', l)
|
Output :
sorted list : ['for', 'geeks', 'geeks']
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:
Python3
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
Total_ordering It is a class decorator that fills in the missing comparison methods (__lt__, __gt__, __eq__, __le__, __ge__). If a class is given which defines one or more comparison methods, “@total_ordering” automatically supplies the rest as per the given definitions. However, the class must define one of __lt__(), __le__(), __gt__(), or __ge__() and additionally, the class should supply an __eq__() method.
Example:
Python3
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
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 = 10 : True
5 == 5 : True
Update_wrapper It updates a wrapper function to look like the wrapped function. For example, in the case of partial functions, we can update the partial function to look like its parent function by using update_wrapper(partial, parent). This will update the documentation(__doc__) and name(__name__) of the partial function to same as of the parent function.
Syntax:
update_wrapper(wrapper, wrapped[, assigned][, updated])
Example:
Python3
from functools import update_wrapper, partial
def power(a, b):
return a**b
pow2 = partial(power, b = 2)
pow2.__doc__=
pow2.__name__ = 'pow2'
print('Before wrapper update -')
print('Documentation of pow2 :', pow2.__doc__)
print('Name of pow2 :', pow2.__name__)
print()
update_wrapper(pow2, power)
print('After wrapper update -')
print('Documentation of pow2 :', pow2.__doc__)
print('Name of pow2 :', pow2.__name__)
|
Output:
Before wrapper update -
Documentation of pow2 : a to the power 2
Name of pow2 : pow2
After wrapper update -
Documentation of pow2 : a to the power b
Name of pow2 : power
Wraps It is a function decorator which applies update_wrapper() to the decorated function. It is equivalent to partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated).
Example:
Python3
from functools import wraps
def decorator(f):
@wraps(f)
def decorated(*args, **kwargs):
"""Decorator's docstring"""
return f(*args, **kwargs)
print('Documentation of decorated :', decorated.__doc__)
return decorated
@decorator
def f(x):
"""f's Docstring"""
return x
print('f name :', f.__name__)
print('Documentation of f :', f.__doc__)
|
Output:
Documentation of decorated : f's Docstring
f name : f
Documentation of f : f's Docstring
LRU_cache LRU_cache is a function decorator used for saving up to the maxsize most recent calls of a function. This can save time and memory in case of repeated calls with the same arguments. If *maxsize* is set to None, the cache can grow without bound. If *typed* is True, arguments of different data types will be cached separately. For example, f(1.0) and f(1) will be memoized distinctly.
Syntax:
lru_cache(maxsize=128, typed=False)
Example:
Python3
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)
SingleDispatch It is a function decorator. It transforms a function into a generic function so that it can have different behaviors depending upon the type of its first argument. It is used for function overloading, the overloaded implementations are registered using the register() attribute.
Example:
Python3
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
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
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
13 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
Functools module is for higher-order functions that work on other functions. It provides functions for working with other functions and callable objects to use or extend them without completely rewriting them. This module has two classes - partial and partialmethod. Partial class A partial function
6 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
Python Time Module
In this article, we will discuss the time module and various functions provided by this module with the help of good examples. As the name suggests Python time module allows to work with time in Python. It allows functionality like getting the current time, pausing the Program from executing, etc. S
8 min read
Python JSON
Python JSON JavaScript Object Notation is a format for structuring data. It is mainly used for storing and transferring data between the browser and the server. Python too supports JSON with a built-in package called JSON. This package provides all the necessary tools for working with JSON Objects i
3 min read
Python Itertools
Python's Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. For example, let's suppose there are two lists and we wa
13 min read
Python Math Module
Math Module consists of mathematical functions and constants. It is a built-in module made for mathematical tasks. The math module provides the math functions to deal with basic operations such as addition(+), subtraction(-), multiplication(*), division(/), and advanced operations like trigonometric
13 min read
Python Operators
In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. OPERATORS: These are the special symbols. Eg- + , * , /,
6 min read
Queue in Python
Like a stack, the queue is a linear data structure that stores items in a First In First Out (FIFO) manner. With a queue, the least recently added item is removed first. A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. Operations
6 min read
Python Random Module
Python Random module generates random numbers in Python. These are pseudo-random numbers means they are not truly random. This module can be used to perform random actions such as generating random numbers, printing random a value for a list or string, etc. It is an in-built function in Python. List
7 min read
Python RegEx
In this tutorial, you'll learn about RegEx and understand various regular expressions. Regular ExpressionsWhy Regular ExpressionsBasic Regular ExpressionsMore Regular ExpressionsCompiled Regular Expressions A RegEx is a powerful tool for matching text, based on a pre-defined pattern. It can detect t
9 min read
Sockets | Python
What is socket? Sockets act as bidirectional communications channel where they are endpoints of it.sockets may communicate within the process, between different process and also process on different places.Socket Module- s.socket.socket(socket_family, socket_type, protocol=0) socket_family-AF_UNIX o
3 min read
Python SQLite
Python SQLite3 module is used to integrate the SQLite database with Python. It is a standardized Python DBI API 2.0 and provides a straightforward and simple-to-use interface for interacting with SQLite databases. There is no need to install this module separately as it comes along with Python after
4 min read
Python sys Module
The sys module in Python provides various functions and variables that are used to manipulate different parts of the Python runtime environment. It allows operating on the interpreter as it provides access to the variables and functions that interact strongly with the interpreter. Let's consider the
6 min read
OS Module in Python with Examples
The OS module in Python provides functions for interacting with the operating system. OS comes under Python's standard utility modules. This module provides a portable way of using operating system-dependent functionality. The *os* and *os.path* modules include many functions to interact with the fi
10 min read
OS Path module in Python
OS Path module contains some useful functions on pathnames. The path parameters are either strings or bytes. These functions here are used for different purposes such as for merging, normalizing, and retrieving path names in Python. All of these functions accept either only bytes or only string obje
2 min read
Generating Random id's using UUID in Python
We had discussed the ways to generate unique id's in Python without using any python inbuilt library in Generating random Id’s in Python In this article we would be using inbuilt functions to generate them. UUID, Universal Unique Identifier, is a python library which helps in generating random objec
3 min read