Python › functools & Functional Programming Tools
How do you use functools.partial to fix keyword arguments for logging or callback functions?
BeginnerAnswer
partial(func, **kwargs) pre-binds keyword arguments, returning a new callable that only needs the remaining arguments when invoked. This is a common pattern for adapting a general-purpose function to an event system or callback API that calls it with a fixed signature.
from functools import partial
import logging
def log(message, level='INFO'):
print(f'[{level}] {message}')
warn = partial(log, level='WARNING')
warn('Disk space low') # [WARNING] Disk space lowReal-world example A task scheduler registers partial(send_email, template='reminder') as the callback so the scheduler only needs to supply the recipient at call time.