Partial Functions

journey into python

Helpful links

What is a Python partial function?

You may construct partial functions in Python utilizing the functools module’s partial function. Partial functions enable you to derive a function with fewer parameters and fixed values for the more limiting function.

For example, suppose you have a function that requires two parameters, and you constantly use it with one of the parameters having a fixed value. In this case, you can derive a new partial function with only one parameter and equivalent to using your original function with the given fixed value.

How do I construct a Python partial function?

To construct a Python partial function, you first need to import the functools module. Next, you use the functools.partial function to create a new function that takes fewer parameters than the original. Finally, you pass in the remaining parameters and their corresponding values.

Here’s an example of how to create a partial function that takes only one parameter:

from functools import partial

def add(a, b):
    return a + b

pf = partial(add, 3)

print(pf(7))
10

Another simple example of how to use a partial function

def sub(c, d, e):
    return c - d - e

pf = partial(sub, 10, 2)

print(pf(7))
1

It’s worth noting that the starting values will begin replacing variables from the left.

Example Above:

  • c is 10
  • d is 2
  • e is 7

Leave a Comment