Write Your Own partial
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?
- Calls
fwith one list and one dict - Calls
f(1, 2, c=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?
{"a": 1, "b": 2}{"a": 1, "b": 9}- 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.)
VISIBLE = 3
CASES = [
('add = lambda a, b, c: a + b + c\np = my_partial(add, 1, 2)\nresult = p(3)', 6, 'frozen positional arguments'),
('def greet(greeting, name):\n return f"{greeting}, {name}!"\np = my_partial(greet, name="Ann")\nresult = (p("Hi"), p("Yo", name="Bo"))', ('Hi, Ann!', 'Yo, Bo!'), 'a frozen keyword argument that can be overridden'),
('p = my_partial(pow, 2)\nresult = [p(n) for n in range(5)]', [1, 2, 4, 8, 16], 'frozen first argument'),
('f = lambda *a, **k: (a, k)\nresult = my_partial(f)()', ((), {}), 'nothing frozen, nothing given'),
('f = lambda *a, **k: (a, k)\np = my_partial(f, 1, x=2)\nresult = p(3, y=4)', ((1, 3), {'x': 2, 'y': 4}), 'both kinds on both sides'),
('parse = my_partial(int, base=2)\nresult = parse("101")', 5, 'a built-in function'),
('f = lambda a, b: a - b\np = my_partial(f, 10)\nresult = (p(3), p(4))', (7, 6), 'the new function can be called more than once'),
]