163. Using functools.partial for Function Customization
Snippet 1: Freezing One Argument in a Function
Copy
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
Copy
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
Copy
Snippet 4: Freezing Function Arguments for Custom Operations
Copy
Snippet 5: Customizing a Power Function
Copy
Snippet 6: Freezing Keyword Arguments
Copy
Snippet 7: Customizing Function for Different Operations
Copy
Snippet 8: Partial Function with Default Arguments
Copy
Snippet 9: Customizing a String Formatter
Copy
Snippet 10: Freezing Arguments in a File Reading Function
Copy
Last updated