Interview frequency: …
Short answer
It creates a new callable that fixes some arguments of an existing function, which helps when passing a callback that needs fixed context.
Explanation
partial is clearer than a lambda when you only want to fix some arguments, and it can be pickled if the original function can (unlike a lambda), which matters when sending tasks to a ProcessPoolExecutor. You can inspect the function and fixed arguments through func, args and keywords. Do not use it to build abstraction layers that hide important dependencies from the reader.
Code example
from functools import partial
from concurrent.futures import ProcessPoolExecutor
def resize(path: str, width: int, quality: int) -> str: ...
thumbnail = partial(resize, width=200, quality=80)
with ProcessPoolExecutor() as pool:
results = list(pool.map(thumbnail, paths))Common mistakes
- Passing a lambda to a ProcessPoolExecutor and getting a PicklingError.
- Fixing positional arguments in the wrong order instead of using keyword arguments.
Follow-up questions
- What is a closure, and what is the late-binding problem inside loops?
- When should you use lambda and when def?