Python for Data Engineers

Partial functions in Python

Constantin LunguUpdated 1 min read

Photo by Rafael Garcin on Unsplash

Have you ever used partial functions? It's an interesting functionality that can be found in the functools package.

It's pretty straightforward - you can take a function that takes multiple arguments and produces a new function that has one or more arguments already set, effectively tailoring your previous function to a specific need.

See below an example of it in action.

from functools import partial

# Raises the number to a power
def power(base, exponent):
    return base ** exponent

# Making specialized versions for squaring and cubing
square = partial(power, exponent = 2)

cube = partial(power, exponent = 3)

print(square(5))  # Output: 25

print(cube(5))    # Output: 125

Enjoyed this? Here are some related articles you might find useful: