Partial Functions in Python

Python : Partial Functions

What is the Partial Functions in Python?

Partial functions are a powerful tool in Python that allow you to create new functions from existing functions with some of the arguments pre-filled. This can be useful in situations where you have a function that takes a lot of arguments, but you want to reuse it with some of those arguments fixed.

In Python, we can use the functools module to create partial functions.

The partial() function in this module takes a function and some of its arguments and returns a new function with those arguments pre-filled.

from functools import partial

# Define a function that takes three arguments
def multiply(x, y, z):
    return x * y * z

# Create a new function with one argument pre-filled
double = partial(multiply, 2)

# Call the new function with two arguments
result = double(3, 4)
print(result)  # Output: 24

Fix arguments in the middle of the argument list using Partial Functions -

# Define a function that takes three arguments
def add(x, y, z):
    return x + y + z

# Create a new function with the second argument pre-filled
add_5 = partial(add, y=5)

# Call the new function with the remaining two arguments
result = add_5(3, 4)
print(result)  # Output: 12
  • Lambda Function is also known as a partial function.
  • Partial functions are a great way to reuse existing functions and reduce code duplication.
  • Partial functions allow us to create new functions quickly and easily by fixing some of the arguments of an existing function.

Previous Article