Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python functools partial() Function



The Python partial() function allows us to create a new function with a specific number of arguments predefined from another function. A partial() function is used to specify a function by reducing the number of parameters it requires. This defining by constant values for the particular number of arguments. It makes the code more reusable without specifying the original function.

Syntax

Following is the syntax for the partial() function.

functools.partial(func, /, *args, **kwargs)

Parameters

The parameters for the partial() function are listed below −

  • / : This indicates that all parameters must be specified positionally.
  • *args : This is the positional argument used to set in advance for the new function.
  • **kwargs : This is the keyword argument used to predefined the new function.

Return Value

This function returns a new object, that behaves like the original function with specified number of arguments.

Example 1

In the below example we are creating a specific version to multiply the arguments that are predefined using the partial() function.

from functools import partial
def multiply(n, p):
    return n*p
x = partial(multiply, 3)
print(x(3))

Output

The result is generated as follows −

9

Example 2

Here, partial() is used to create a new function and this calculates a result that is based on the formula below.

from functools import partial
def func(m, n, o, p):
    return m*1 + n*2 + o*3 + p
x = partial(func, 4, 5, 6)
print(x(7))

Output

The code is generated as follows −

39

Example 3

In the example below, we are using the predefined values for x and y, while add function takes a single argument, which is the variable z.

from functools import *
def add(w, x, y):
    return 1000*w + 100*x + y
add_part = partial(add, y = 3, x = 2)
print(add_part(2))

Output

The output is obtained as follows −

2203
python_modules.htm
Advertisements