Partial Functions in Python
A partial function is derived from an existing function by pre-filling (or “fixing”) some of its arguments with specific values. This creates a new function that behaves like the original but with fewer arguments to supply. In Python, you create them using functools.partial(func, *args, **kwargs)
.
Core Uses & Benefits
Partial functions enhance code reusability by allowing you to create specialized versions of general functions. They improve readability by giving these pre-configured functions meaningful names. They are also valuable for customizing callbacks by pre-supplying necessary arguments while still matching an expected function signature.
Examples
Fixing a positional argument
Configuring specialized functions by fixing keyword arguments
import functools
def send_notification(message, recipient, channel):
print(f"Sending to {recipient} via {channel}: {message}")
# Pre-configure notifiers for different channels
email_notifier = functools.partial(send_notification, channel="email")
sms_notifier = functools.partial(send_notification, channel="sms")
# Later, use the specialized notifiers
email_notifier(recipient="user@example.com", message="Your order has shipped!")
# Output: Sending to user@example.com via email: Your order has shipped!
sms_notifier(recipient="+1234567890", message="Meeting reminder at 2 PM.")
# Output: Sending to +1234567890 via sms: Meeting reminder at 2 PM.