In this post I’ll be talking about partial functions and how we can use them to make our code cleaner.

1. What can partial functions do for us?
• A partial function allows us to call a second function with fixed values in certain arguments. For instance, we may have a function that computes an exponentiation. Then, we may need to create a new function that assigns a fixed value to either the base or the exponent. We can easily do this by using functool’s partial function, without having to replicate the body of the original function. Let’s go through the implementation of the above example to get a better understanding.
2. # Implementing a partial exponentiation function

• First of all, we’ll need the function from which the partial function will be based on. As mentioned before, we’ll implement an exponentiation function:
```def power(base, exponent):
return base ** exponent```
• Now, we may want to implement a function that computes the squared value of a number. If we didn’t have partial functions available in Python, we’d have to replicate (and adapt) our code:
```def squared(base):
return base ** 2```
• In this case, it wasn’t much of a big deal, since we only had to replicate one line of code. However, in most situations, you’ll have to deal with larger functions. Let’s see how to reuse “power()” with a partial function:
```from functools import partialdef power(base, exponent):
return base ** exponentsquared = partial(power, exponent=2)```
• Finally, we may call “squared()” as simply as follows:
```squared(3)
squared(base=7)```

That’s it! I hope that partial functions become a useful tool for you and help you reduce complexity in your code!

Related Articles