Sitemap

Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Partial Functions in Python

Python Shorts — Part 8

2 min readJan 9, 2023

--

Assume you have a function foo with a long argument list, and frequently use this in your code. It is tedious to always spell out the full call to foo — especially if some of the arguments are shared between calls. This is a common pattern: you might define a general, low-level function foo(a, b, c, d)— and then re-use this function from different modules A and B. From A you always call foo(A1, A2, A3, x), and from B foo(B1, B2, B3, y). In these cases, or whenever you want to simplify and encapsulate usage of a function, functools.partial is the perfect helper: it allows to define a new function fixing certain arguments.

Press enter or click to view image in full size
Photo by David Clode on Unsplash

functools is a powerful module offering lots of handy functionality. In a previous post we already saw the lru_cache decorator — here we will introduce partial, which allows to define “partial functions”: we can define new functions from an existing one, fixing some of the arguments.

The following code defines foo_partial, which is a new function derived from foo with the arguments a = “a1”, b = “b1”, c = 1:

from functools import partial


def foo(a, b, c, d):
print(f"Calling foo with: {a}, {b}, {c}, {d}")


foo_partial = partial(foo, "a1", "b1", 1)

foo_partial("d")

foo_partial can then be called with the only remaining argument, d. Note that we can only fix the first N arguments of a function — thus you have to set the parameter order accordingly — and the last M parameters can be left open.

Get Oliver S’s stories in your inbox

Join Medium for free to get updates from this writer.

Let’s finish with another example introducing named functions for the first 3 powers:

from functools import partial


def exponentiate(base: int, exponent: float) -> float:
return base**exponent


square = partial(exponentiate, 2)
cube = partial(exponentiate, 3)
biquadrate = partial(exponentiate, 4)

This post is part of a series show-casing important Python concepts quickly. You can find the other parts here:

--

--

Level Up Coding
Level Up Coding
Oliver S
Oliver S

Written by Oliver S

PhD in ML, working as research / software engineer