FANDOM


What is it? Edit

partial is a tool within the functools module. Partial functions allow us to fix a certain number of arguments of a function and generate a new function.


Example:

from functools import partial

# A normal function
def f(a, b, c, x):
    return 1000 * a + 100 * b + 10 * c + x

# A partial function that calls f with a as 3, b as 1, and c as 4.
g = partial(f, 3, 1, 4)

# Calling g()
print(g(5))


# Output :
3145

In the example above we have pre-filled our function with some constant values of a, b, and c. And g() just takes a single argument i.e the variable x.

Example of useEdit

I have previously used the partial function tool when needing to pass a function with arguments to another function.

For example, I wanted to be able to pass functions with certain arguments to another function when pressing a button in my UI.  In the code below I used partial functions to pass the takeLife() function with a given string argument to the .clicked.connect() function of a button, so I would know which player I was deducting points from based on the button pressed :

# Tracking the subtracting and adding of life points.
self.ui.TakeLife02_pushButton.clicked.connect(partial(self.takeLife, "player02"))
self.ui.TakeLife01_pushButton.clicked.connect(partial(self.takeLife, "player01"))

Breaking it down:

When we want to call a certain function when a button has been pressed for instance, we would write something like:

someButton.clicked.connect(someFunction)

See how we don't use the braces, because we want to run the function when the button is clicked. Not whenever the application is run. But how do we do the above if we need to pass arguments to the "someFunction"? Well we can't do this:

someButton.clicked.connect(someFunction("a string"))

So this is where partial functions come in handy!

someButton.clicked.connect(partial(someFunction, "a string"))

ReferencesEdit

Partial Functions in Python - GeeksforGeeks

Passing functions with arguments to another function in Python? - Stackoverflow

Community content is available under CC-BY-SA unless otherwise noted.