Fewer Arguments, Same Function? Python's functools.partial

This article explains how Python's functools.partial fixes some arguments of a function, how stored and new arguments combine, how it adapts functions to callbacks and methods, and which pitfalls and costs it brings.

A bright green tree python raises its head above its coils on a branch, lit against a dark brown background.
Photo by Sulhan Aldani on Unsplash

Functions that take several arguments are often called many times with the same values for some of them, and APIs such as map, sorted or callback registries accept functions with fewer parameters than the one available. The present article addresses functools.partial, which fixes some arguments of a callable and returns a new callable for the rest. Many shooters provide an appropriate image: a player saves a loadout with a weapon and its attachments already chosen, so that at each respawn only the remaining decisions are left. This means that a partial object stores the function together with the arguments already decided and, when called, adds the new arguments to them before calling the original function. The analogy, however, stops at this point, because a loadout can be replaced entirely, whereas a positional argument fixed in a partial object can never be overridden, and a fixed keyword argument can be overridden without any warning. The article describes how the stored arguments combine with new ones, applies the tool to callbacks and methods, measures its cost against a lambda, and identifies the errors it introduces. Deriving a specialized function from a general one without writing a new def is the secret weapon of functools.partial.

How Stored Arguments Combine

A partial object keeps three read-only attributes: func, the original callable, args, the positional arguments placed before those of the call, and keywords, the keyword arguments merged with those of the call, where the caller's values win. Applying partial to a partial object flattens the result into a single object, and inspect.signature reports the parameters that remain. The following example shows these rules.

import inspect
from functools import partial


def price_with_tax(price, tax_rate):
    return round(price * (1 + tax_rate), 2)


with_vat = partial(price_with_tax, tax_rate=0.21)
print(with_vat(100), with_vat(100, tax_rate=0.10))  # Output: 121.0 110.0
print(inspect.signature(with_vat))                  # Output: (price, *, tax_rate=0.21)

hundred = partial(price_with_tax, 100)
try:
    hundred(price=50)
except TypeError as error:
    print(error)  # Output: price_with_tax() got multiple values for argument 'price'

nested = partial(partial(price_with_tax, 100), tax_rate=0.05)
print(nested.func is price_with_tax, nested.args, nested.keywords)
# Output: True (100,) {'tax_rate': 0.05}

The fixed keyword becomes a keyword-only parameter with a default, so the caller may replace it, whereas the fixed positional argument occupies price permanently and a second value for it is an error. Python 3.14 adds functools.Placeholder, which reserves a positional slot so that later positions can be fixed while earlier ones remain open, as in partial(str.replace, Placeholder, Placeholder, ""); every placeholder must then be filled when the object is called.

Adapting Functions to Callbacks and Methods

Partial objects are most useful where an API dictates the shape of the callable. Unlike a lambda, they bind their values at creation, which avoids the late-binding error of lambdas created in loops described in the article devoted to the Strategy pattern, and they can be pickled whenever the wrapped function can, which matters for multiprocessing. Inside a class body, functools.partialmethod, available since Python 3.4, produces methods that receive self correctly. The following example shows the three uses.

import pickle
from functools import partial, partialmethod

print(list(map(partial(int, base=2), ["101", "11", "1000"])))  # Output: [5, 3, 8]


def scale(value, factor):
    return value * factor


double = partial(scale, factor=2)
restored = pickle.loads(pickle.dumps(double))
print(restored(21))  # Output: 42
try:
    pickle.dumps(lambda value: scale(value, 2))
except pickle.PicklingError:
    print("a lambda cannot be pickled")  # Output: a lambda cannot be pickled


class Light:
    def __init__(self):
        self.on = False

    def set_state(self, state):
        self.on = state

    turn_on = partialmethod(set_state, True)
    turn_off = partialmethod(set_state, False)


lamp = Light()
lamp.turn_on()
print(lamp.on)  # Output: True

The conversion from binary needs only the strings because base is fixed, the partial object survives a round trip through pickle while the equivalent lambda does not, and the two methods of Light share one implementation. Stored requests that are executed later, a related use of the same object, are examined in the article devoted to the Command pattern.

Pitfalls of functools.partial

A partial object hides some arguments from the reader of the call site, so its pitfalls come from forgetting what was fixed, how it was fixed and what the object lacks compared with a function. Six pitfalls are distinguished, which are the following:

  1. Fixed positions. A positional argument fixed in the object cannot be passed again, even by keyword, without TypeError.
  2. Silent overrides. A fixed keyword argument is replaced by the caller's value without any warning.
  3. Shared mutable arguments. A list or dictionary fixed in the object is the same object in every call.
  4. No name or docstring. Partial objects have no __name__ or __doc__, which breaks code that logs or registers functions by name.
  5. Keyword cost. On CPython 3.12, calling a partial object with fixed keywords was slower than an equivalent lambda.
  6. Methods. A partial object assigned in a class body is not the tool designed for methods; partialmethod is.

The third, fourth and fifth pitfalls are reproduced in the following example.

import timeit
from functools import partial, update_wrapper


def append_to(item, target):
    target.append(item)
    return target


collect = partial(append_to, target=[])
collect("a")
print(collect("b"))  # Output: ['a', 'b']

print(hasattr(collect, "__name__"))  # Output: False
update_wrapper(collect, append_to)
print(collect.__name__)  # Output: append_to


def price_with_tax(price, tax_rate):
    return price * (1 + tax_rate)


fixed_keyword = partial(price_with_tax, tax_rate=0.21)
same_lambda = lambda price: price_with_tax(price, tax_rate=0.21)
t_partial = min(timeit.repeat("f(100)", globals={"f": fixed_keyword}, number=1_000_000, repeat=5))
t_lambda = min(timeit.repeat("f(100)", globals={"f": same_lambda}, number=1_000_000, repeat=5))
print(t_partial > t_lambda)  # Output: True

The second call found the item left by the first, because both used the single list created when the partial object was built. update_wrapper copies the name and the docstring of the wrapped function, the same mechanism that decorators use through functools.wraps. On CPython 3.12, a call with a fixed keyword argument took about 107 nanoseconds against 65 for the lambda, while a partial object with only positional arguments matched the lambda at about 58, so the common claim that partial objects are faster than lambdas does not hold in general.

Choosing How to Specialize a Function

Consequently, functools.partial suits callables whose arguments are known in advance and must be passed to code that expects fewer parameters, as the following table summarizes.

Situation Recommended approach
Fixing leading positional or any keyword arguments functools.partial
Fixing a later positional argument, Python 3.14 partial with functools.Placeholder
Several methods that share one implementation functools.partialmethod
Callables sent to other processes partial over a module-level function, not a lambda
Reordering arguments or adding logic A lambda or a named function
A specialization used throughout a program A named function with its own docstring

Conclusion

It is concluded that functools.partial stores a function with some of its arguments, prepends the fixed positional ones, merges the keywords in favour of the caller, and flattens nested applications into one object. This magic is limited: fixed positions cannot be overridden, fixed keywords can be overridden silently, mutable arguments are shared between calls, and the object has no name of its own. Keeping a table of classes or functions that register themselves under a name, so that new variants can be added without editing a central dispatcher, is the purpose of the Registry pattern, which is developed in a future article of this series.