functools.partial creates a new function with some arguments pre-filled.
1from functools import partial23def power(base, exponent):4 return base ** exponent56# Create specialized functions7square = partial(power, exponent=2)8cube = partial(power, exponent=3)910print(square(5)) # 2511print(cube(5)) # 1251213# With maps14map(square, [1, 2, 3, 4]) # [1, 4, 9, 16]1516# In callbacks17def process(data, callback):18 result = transform(data)19 callback(result)2021process(data, partial(save_to_db, table="users"))2223# With class methods24from operator import methodcaller25strip = methodcaller("strip")26strip(" hello ") # "hello"
Benefits: