Partial Functions in Python: A Guide for Developers


Partial Functions in Python: A Guide for Developers
Image by Author | Snappify

 

In Python, functions often require multiple arguments, and you may find yourself repeatedly passing the same values for certain parameters. This is where partial functions can help.

Python’s built-in functools module allows you to create partial functions. Creating partial functions allows you to fix some of the arguments of a function and create a new, more concise version.

This tutorial will teach you how to use partial functions effectively to make your code cleaner and more efficient.

 

What are Partial Functions, And Why Should You Use Them?

 

A partial function is a new function derived from an existing function where one or more arguments are pre-set, or “fixed”. When you call the new partial function, you only need to pass in the remaining arguments. Partial functions are part of the functools module in Python and give the following advantages:

  • Simplified function calls: With partial functions, you can fix commonly used arguments in a function to avoid passing them repeatedly.
  • Improved code readability: Create specialized versions of functions that are easier to understand and use.
  • Reusability: Generate multiple variants of a function for different purposes with minimal repetition.

To create a partial function, you use partial from the functools module like so:

from functools import partial

# Syntax
partial_function = partial(original_function, fixed_arg1, fixed_arg2, ...)

 

Here, original_function is the function you’re modifying, and fixed_arg1, fixed_arg2, ... are the arguments you want to pre-set.

Now let’s get to coding a few examples. You can find these examples on GitHub.

 

Example 1: Simplifying a Mathematical Function

 

Let’s say you have a function to calculate the power of a number, and you often need to square numbers.

Instead of passing 2 as the exponent each time, you can use a partial function to create a custom version that always squares the input.

from functools import partial

# Original function to compute power
def power(base, exponent):
    return base ** exponent

# Create a partial function that always squares the base
square = partial(power, exponent=2)

 

Now, you can call the square function without specifying the exponent as shown:

print(square(5))  
print(square(9)) 

 

Which outputs:

 

Example 2: Handling Keyword Arguments with Partial Functions

 

Partial functions work not only with positional arguments but also with keyword arguments. Here’s an example of a function that formats text and allows alignment customization.

from functools import partial

def format_text(text, alignment="left", width=80):
    if alignment == "center":
        return text.center(width)
    elif alignment == "right":
        return text.rjust(width)
    else:
        return text.ljust(width)

 

You can create a partial function to center-align the text by default:

# Create a partial function for center alignment with a specific width
centered_text = partial(format_text, alignment="center", width=50)

# Use the partial function without passing alignment or width
print(centered_text("Partial Functions")) 

 

In this example, the centered_text partial function fixes both the alignment and width, so you only need to provide the text to get the required output:

 

Example 3: Partial Functions in Data Processing

 

Partial functions are particularly useful in data processing tasks. Suppose you have a function to scale data by a factor, and you often scale by specific factors like 2 or 10.

As you might already be familiar by now, partial functions allow you to create new functions for specific scaling operations.

from functools import partial

# Function to scale a value
def scale_data(value, factor):
    return value * factor

# Create partial functions for specific scaling factors
scale_by_2 = partial(scale_data, factor=2)
scale_by_10 = partial(scale_data, factor=10)

data = [1, 2, 3, 4, 5]
scaled_by_2 = list(map(scale_by_2, data))   # Scales by 2
scaled_by_10 = list(map(scale_by_10, data))  # Scales by 10

print(scaled_by_2)  
print(scaled_by_10)  

 

Here, scale_by_2 and scale_by_10 are partial functions that simplify the repetitive task of specifying the scaling factor each time you process data.

Output:

[2, 4, 6, 8, 10]
[10, 20, 30, 40, 50]

 

Example 4: Combining Partial Functions and Lambdas

 

You can also combine partial functions and lambda functions to make your code more concise. Let’s create a partial function for scaling values, but this time using a lambda:

from functools import partial

# Use lambda with partial to create a custom scaling function
scale = partial(lambda x, factor: x * factor, factor=3)

# Apply the partial function to a list of numbers
scaled_values = [scale(i) for i in range(1, 6)]
print(scaled_values)  

 

This outputs:

 

This approach combines the flexibility of lambda functions with partial functions, providing a compact and clear way to scale values.

 

When to and When Not to Use Partial Functions

 

Let’s now go over when you should and when not to use partial functions.

You can use partial functions when you:

  • Repeatedly use the same argument values for a function and want to avoid repetition
  • Need to generate multiple specialized versions of a function for different use cases
  • Want to improve code readability by creating simpler, more specific function calls

But like most features in Python, make sure you don’t overuse or needlessly reduce readability:

  • If you find partial functions making the code harder to understand, or if their use adds complexity, reconsider using them.
  • If fixing arguments doesn’t meaningfully improve clarity or reduce code repetition, regular functions may be a better choice.

 

Wrapping Up

 

Partial functions can simplify and improve your Python code by fixing arguments and creating specialized versions of functions.

You can make your function calls more concise, improve readability, and reduce repetition in cases where certain arguments remain constant. But be sure not to overuse them or use them when not necessary.

If you need some help on writing functions, read 5 Tips for Writing Better Python Functions.
 
 

Bala Priya C is a developer and technical writer from India. She likes working at the intersection of math, programming, data science, and content creation. Her areas of interest and expertise include DevOps, data science, and natural language processing. She enjoys reading, writing, coding, and coffee! Currently, she’s working on learning and sharing her knowledge with the developer community by authoring tutorials, how-to guides, opinion pieces, and more. Bala also creates engaging resource overviews and coding tutorials.

Our Top 3 Course Recommendations

1. Google Cybersecurity Certificate – Get on the fast track to a career in cybersecurity.

2. Google Data Analytics Professional Certificate – Up your data analytics game

3. Google IT Support Professional Certificate – Support your organization in IT



Recent Articles

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here