Partial application lets you lock in one or more arguments to a function. It gives you a new function that only takes the remaining, as-yet-to-be-specified arguments. If arguments are applied against a function, then partial application allows you to apply only some of them - that is, you can partially apply them. Later on, you can finish out the argument application.
One can also read the Python docs.
from functools import partial
def add(a, b):
return a + b
add10 = partial(add, 10)
add10(1) # 11
The add10
function above is equivalent to:
def add10(b):
return add(10, b)
Consider a thing that can be configured and then used. The usual OO pattern is to create a class, like so:
class Thing:
def __init__(self, some_parameter=''):
self.some_parameter = some_parameter
def do_the_thing(self, n):
print(n * 'I am {}. '.format(self.some_parameter))
cool_thing = Thing(some_parameter="cool")
cool_thing.do_the_thing(2) # 'I am cool. I am cool.'
hot_thing = Thing(some_parameter="hot")
hot_thing.do_the_thing(3) # 'I am hot. I am hot. I am hot.'
But you could also try out partial application:
def do_the_thing(n, some_parameter=''):
print(n * 'I am {}. '.format(some_parameter))
cool_thing = partial(do_the_thing, some_parameter="cool")
cool_thing(2) # 'I am cool. I am cool.'
hot_thing = partial(do_the_thing, some_parameter="hot")
hot_thing(3) # 'I am hot. I am hot. I am hot.'
The Python implementation of partial application can be found here.