Introduction
Partial application is a technique for fixing some arguments of a function, creating a new function with fewer parameters. The functools.partial module provides this capability.
Basic partial
from functools import partial
def multiply(a, b, c):
return a * b * c
# Fix the first argument
double = partial(multiply, 2)
print(double(3, 4)) # 24
# Fix multiple arguments
always_five = partial(multiply, 2, 2, 1)
print(always_five()) # 4
Partial with Keywords
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
print(square(5)) # 25
print(cube(2)) # 8
Using partial in Data Processing
from functools import partial
def apply_tax(amount, tax_rate):
return amount * (1 + tax_rate)
apply_10_percent = partial(apply_tax, tax_rate=0.10)
apply_20_percent = partial(apply_tax, tax_rate=0.20)
prices = [100, 200, 300]
with_tax = list(map(apply_10_percent, prices))
print(with_tax) # [110, 220, 330]
Partial for Event Handlers
from functools import partial
def handle_click(button_id, event):
print(f"Button {button_id} clicked at {event.x}, {event.y}")
button1_handler = partial(handle_click, "button1")
button2_handler = partial(handle_click, "button2")
# In event loop
button1_handler(mouse_event)
Functional Partial
from functools import partial
class Partial:
def __init__(self, func, *args, **kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
def __call__(self, *args, **kwargs):
combined_args = self.args + args
combined_kwargs = {**self.kwargs, **kwargs}
return self.func(*combined_args, **combined_kwargs)
def map(self, func):
return Partial(lambda *a, **kw: func(self(*a, **kw)))
Practice Problems
- Create partial function for string formatting
- Use partial in map/filter operations
- Create partial with keyword arguments
- Implement custom partial class
- Use partial for callback handlers