163. Using functools.partial for Function Customization

Snippet 1: Freezing One Argument in a Function

from functools import partial

# Function that adds two numbers
def add(a, b):
    return a + b

# Freeze the value of 'a' to 10
add_10 = partial(add, 10)

# Call the partially frozen function
result = add_10(5)  # This will add 10 + 5
print(f"Result: {result}")

Snippet 2: Freezing Multiple Arguments

from functools import partial

# Function that adds three numbers
def add_three(a, b, c):
    return a + b + c

# Freeze 'a' to 5 and 'b' to 10
add_5_and_10 = partial(add_three, 5, 10)

# Call the partially frozen function
result = add_5_and_10(15)  # This will add 5 + 10 + 15
print(f"Result: {result}")

Snippet 3: Customizing a Logging Function


Snippet 4: Freezing Function Arguments for Custom Operations


Snippet 5: Customizing a Power Function


Snippet 6: Freezing Keyword Arguments


Snippet 7: Customizing Function for Different Operations


Snippet 8: Partial Function with Default Arguments


Snippet 9: Customizing a String Formatter


Snippet 10: Freezing Arguments in a File Reading Function


Last updated