Hard: Advanced Interview · Problem 67 of 82

Write Your Own partial

HardFunctionsPython

Write my_partial(func, *args, **kwargs) that returns a new function. When the new function is called, it calls func with:

  • the frozen positional arguments first, then the positional arguments of the new call,
  • the frozen keyword arguments, which the keyword arguments of the new call can override.

This is what functools.partial does.

Understand the problem

Revise unpacking with * and ** in a call.

What does f(*[1, 2], **{"c": 3}) do?

  1. Calls f with one list and one dict
  2. Calls f(1, 2, c=3)
  3. Raises an error

* unpacks a sequence into positional arguments and ** unpacks a dictionary into keyword arguments. These are the two tools this problem needs in a call.

{**{"a": 1, "b": 2}, **{"b": 9}}: what is the result?

  1. {"a": 1, "b": 2}
  2. {"a": 1, "b": 9}
  3. An error

When two unpacked dictionaries share a key, the later one wins. That is the way to let the new call's keyword arguments override the frozen ones: put them last.

Write the solution

Return the new function.

def my_partial(func, *args, **kwargs):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

What must the inner function remember, and what does it receive when it is called?

Hint 2: the shape of the answer

An inner function new(*more_args, **more_kwargs) that returns func(*args, *more_args, **{**kwargs, **more_kwargs}).

Reflect

Solution

def my_partial(func, *args, **kwargs):
    def new(*more_args, **more_kwargs):
        return func(*args, *more_args, **{**kwargs, **more_kwargs})
    return new

Another way: the standard library

from functools import partial

def my_partial(func, *args, **kwargs):
    return partial(func, *args, **kwargs)

What this tests: *args and **kwargs both when defining and when calling, closures, and merging dictionaries.

Order of arguments: the frozen positionals go first, the new ones after. Frozen keywords go first in the merge so that the call can override them.

Where partial is used: callbacks (button.on_click(partial(handle, id=3))), map with a fixed argument (map(partial(pow, 2), range(5))), and building specialised versions of general functions (parse_int = partial(int, base=2)).

A lambda does the same for one case (lambda x: pow(2, x)); partial is cleaner when the arguments are variable.

What an interviewer might ask next: Make the frozen arguments visible, as functools.partial does with .args and .keywords. (Attach them to the inner function as attributes.)