Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Standard library & toolingMiddleOccasionalPractical

What does `functools.partial` do, and why prefer it over a small `lambda` wrapper?

Answer

`functools.partial(func, *args, **kwargs)` returns a new callable that, when eventually called, invokes `func` with those pre-supplied arguments already filled in, plus whatever additional arguments are provided at call time. Unlike a `lambda x: func(fixed_arg, x)` wrapper, a `partial` object retains introspectable references to the original function and its bound arguments (`.func`, `.args`, `.keywords`), and communicates intent — "this is `func` with some arguments already fixed" — more directly than an ad-hoc wrapper function. It also plays well with `pickle` in multiprocessing contexts where a local lambda would fail outright, provided the wrapped callable and its bound arguments are themselves picklable — a `partial` wrapping an unpicklable callable or argument does not become picklable just by being wrapped.

Strong answer includes

  • returns a callable with some arguments pre-filled, remaining ones supplied at call time
  • retains introspectable .func/.args/.keywords, unlike an opaque lambda
  • pickle-friendliness for multiprocessing depends on the wrapped callable and bound arguments themselves being picklable

Practical example

Python example
double = functools.partial(multiply, 2)

behaves exactly like

Python example
double(5) == 10

, and

Python example
pool.map(functools.partial(process, config), items)

works safely across process boundaries where

Python example
lambda x: process(config, x)

would raise a pickling error.

#functools#functional-programming

Sources

functools — Higher-order functions and operations on callable objectsPython Software Foundation · lru_cache, partial, wraps, reduce and singledispatch behaviormultiprocessing — Process-based parallelismPython Software Foundation · Process pools, pickling constraints and inter-process communication