What is functools.partial and when would you use it?
`functools.partial` is a higher-order function that creates a new callable with some arguments of an existing function pre-filled (partially applied). Calling the resulting partial object supplies the remaining arguments.
Basic usage:
```python from functools import partial
def power(base, exponent): return base ** exponent
square = partial(power, exponent=2) cube = partial(power, exponent=3)
square(5) # 25 cube(4) # 64 ```
The `partial` object stores a reference to the original function, the pre-filled positional args, and keyword args. When called, it merges the stored args with the new args and invokes the original function.
**When to use it**:
1. **Callback adaptation**: When a callback signature is fixed (e.g., `button.on_click(callback)` expects `callback(event)`) but you need to pass extra context. `partial(handler, user_id=current_user.id)` creates a bound callback without a lambda.
2. **Creating specialized versions of general functions**: `int_from_hex = partial(int, base=16)` creates a specialized int parser. This is more explicit and picklable than a lambda.
3. **`map`/`filter` integration**: `list(map(partial(operator.mul, 2), [1, 2, 3]))` — more readable than a lambda for simple transformations.
4. **Reducing arity for APIs expecting fewer arguments**: When a library expects a `f(x)` but you have a `g(x, config)` and want to pin `config`.
**Partial vs. lambda**: Both achieve partial application. `partial` is preferred when: the function is already named (no anonymous behavior), the result needs to be picklable (lambdas aren't—`partial` objects are), and introspection matters (`partial` preserves `func`, `args`, `keywords` attributes). Lambdas are better for one-line transformations that benefit from inline readability.
`functools.partialmethod` is the class-method equivalent—used when you want to create a method on a class with some arguments pre-bound, useful for creating specialized versions of base class methods.
Correctly explains partial application, demonstrates basic usage, gives two concrete use cases, mentions the pickleability advantage over lambda.
Explains the internal storage mechanism (func, args, keywords), contrasts partial with lambda with specific guidance on when to prefer each, mentions partialmethod, and gives a realistic callback-binding or map/filter example.
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment