A partial accepts a callable object, args, and kwargs. You can then call that partial as you would call the object, passing whatever remaining args and kwargs necessary. This allows for creating "templates" of callable objects with base arguments that can be called in various places that need varying values to pass in, which reduces some of the repetition of calling the same object multiple times with a bunch of the same arguments with the same values and other arguments with different values, which also reduces the potential for human error.
from functools import partial
def greeting(salutation, colloquial_salutation="sup"):
return salutation, colloquial_salutation
greeting = partial(greeting, "how do you do")
print(greeting(colloquial_salutation="hi"))
print(greeting(colloquial_salutation="howdy"))
print(greeting(colloquial_salutation="yo"))
print(greeting(colloquial_salutation="hey"))
This came in particularly useful where I had to pass a class instance into the decorators of a series of API operation definitions. The class shared 2 of the same parameter values, but the third varied. Rather than:
@decorator(kwarg=Class(variable1="blah", variable2="bleh", variable3="bluh"))
def operation():
...
@decorator(kwarg=Class(variable1="blah", variable2="bleh", variable3="bloh"))
def operation2():
...
# Repeat ad nauseam
Repeating this 150 times creates a lot of opportunity for typos and copy/paste mistakes, and it's just a pain in the patootie. It also results in a ton of repetition that has to be maintained. If one value has to be changed for all operations, then I will have one very unhappy Indian thinking of ways to fuck me in the future. So, instead:
from functools import partial
class = partial(Class, variable1="blah", variable2="bleh")
@decorator(kwarg=class(variable3="bluh"))
def operation():
...
@decorator(kwarg=class(variable3="bloh"))
def operation2():
...
# Repeat ad nauseam
Now, if something needs to change, then I still have one very unhappy Indian thinking of ways to fuck me in the future, but I also got to use functools.partial, an official gyrate dot org 😎⚒️ VERY COOL PYTHON TOOL ⚒️😎.
This has been another educational 😎⚒️ VERY COOL PYTHON TOOL ⚒️😎 post brought to you by gyrate dot org‼️