Partial Functions in Python

Python Methods and Functions

Example :

from functools import partial

 
# Normal function

def f (a, b, c, x ):

return 1000 * a + 100 * b + 10 * c + x

  
# A partial function that calls f with
# a as 3, b as 1 and c as 4.

g = partial (f, 3 , 1 , 4 )

 
# Call g ()

print (g ( 5 ))

Output :

 3145 

In this example, we pre-filled our function with some constant values ​​a, b and c. And g () just takes one argument, i.e. variable x.

Another example:

from functools import *

 
# Normal function

def add (a, b, c):

return 100 * a + 10 * b + c

 
# Partial function with b = 1 and c = 2

add_part   = partial (add, c = 2 , b = 1 )

 
# Partial function call

print (add_part ( 3 ))

Exit:

 312 

Tutorials