Using Partial Functions and Lambda Expressions

Lesson Introduction

Welcome! In modern Python development, creating flexible and reusable code is essential for building highly maintainable applications. One powerful tool to aid in this is the functools.partial function, which allows you to create new callable objects by fixing some portion of the arguments taken by a function. By the end of this lesson, you will understand functools.partial, learn its syntax, explore its usage, and become familiar with lambda expressions as an alternative.

Example Using functools.partial

functools.partial is part of the functools module in Python. It allows you to bind one or more arguments to a function, creating new callable objects. These callable objects can then be invoked just like regular functions. Binding defines the values for the arguments but doesn’t invoke the function immediately. The function is invoked only when the new callable object is called. We have created such functions manually in the previous lesson; functools.partial can help you achieve the same result faster and easier!

Here's an example to understand functools.partial:

from functools import partial

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

# Using functools.partial to create a new function that always adds 5
add_five = partial(add, b=5)
print(f"3 + 5 = {add_five(3)}")  # Output: 3 + 5 = 8

In this example:

  • add is a function that takes two integers (int) and returns their sum.
  • functools.partial creates add_five by binding the second argument b of add to 5.
  • Calling add_five(3) results in add(3, 5), producing 8.

By using partial, we say: "Hey, fix the value of b to 5, but the value of a will be provided later."

Potential Pitfalls

The functools.partial doesn't automatically map positional arguments to the remaining parameters correctly if they clash. If you want to fix not the last argument with partial, you need to ensure that you are not accidentally passing multiple values for it. Here’s how you can do it correctly:

from functools import partial

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

# Using functools.partial to create a new function that always adds 5 as the first argument
add_five = partial(add, a=5)
print(f"5 + 3 = {add_five(b=3)}")  # Output: 5 + 3 = 8

If we fix a, we must pass b by name, using add_five(b=3).

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal