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
double = functools.partial(multiply, 2)behaves exactly like
double(5) == 10, and
pool.map(functools.partial(process, config), items)works safely across process boundaries where
lambda x: process(config, x)would raise a pickling error.