44. Using functools.partial

Here are 10 Python code snippets demonstrating how to use functools.partial to create partially-applied functions, which simplify your code and increase reuse:

1. Basic Partial Function

Create a partial function with some arguments fixed.

Copy

from functools import partial

def multiply(a, b):
    return a * b

# Create a new function with the second argument fixed
double = partial(multiply, b=2)

print(double(5))  # Output: 10

In this example, double is a partially-applied version of multiply with b fixed to 2.


2. Partially Apply Multiple Arguments

Partially apply multiple arguments at once.

Copy

from functools import partial

def power(base, exponent):
    return base ** exponent

# Create a function where the exponent is fixed to 3
cube = partial(power, exponent=3)

print(cube(4))  # Output: 64

Here, cube is a function that calculates the cube of a number, where exponent is pre-set.


3. Default Arguments with Partial

Use partial to create a function with default arguments.

Copy

This code sets the message argument to "Hi" by default, while still allowing the name to vary.


4. Using Partial for Callbacks

Use partial to create a callback function with preset arguments.

Copy

Here, the button is fixed to "Save", and only the action varies when calling button_click.


5. Simplify Function Calls with Partial

Simplify repeated function calls with similar arguments.

Copy

By fixing the level to "INFO", you create a more specialized function for logging information.


6. Partial for Sorting with Custom Key

Use partial to simplify sorting with a custom sorting key.

Copy

This example creates a reusable sort_by_age function that sorts dictionaries by the "age" key.


7. Function Composition with Partial

Use partial to compose a series of functions.

Copy

You can compose different functions using partials for code simplification and reuse.


8. Partial for File Handling

Use partial for common file-handling tasks with preset parameters.

Copy

The read_binary function is a simplified version of read_file with the mode argument fixed to 'rb'.


9. Using Partial to Simulate Method Binding

Simulate method binding with partial.

Copy

Here, say_hello is a version of greeter.greet that always uses the greeting "Hello".


10. Partial for Handling Database Queries

Use partial to handle repeated queries in a database-like application.

Copy

By using partial, we avoid repeating the table="users" argument in multiple queries.


These examples show how functools.partial can be used to simplify your code by creating specialized versions of functions, improving reusability, and reducing repetitive boilerplate.

Last updated