#301 · Functions · Intermediate · 70 XP · about 12 min
functools.partial fixes some arguments of a function in advance: partial(int, base=2) is a function that reads binary numbers. Build your own version without functools.
Write partial(func, *args, **kwargs) that returns a new function p. Calling p(*more_args, **more_kwargs) calls func with:
args first, then more_args, andkwargs together with more_kwargs. When both give the same keyword, the one passed in the call wins, for that call only: the stored keywords never change.It returns what func returns. The new function also carries three attributes that describe it: p.func (the original function), p.args (a tuple of the stored positional arguments) and p.keywords (a dict of the stored keyword arguments).
from_binary = partial(int, base=2) from_binary('1010') # returns 10 power_of_two = partial(pow, 2) power_of_two(10) # returns 1024 def tag(text, open='<', close='>'): return open + text + close square = partial(tag, open='[', close=']') square('x') # returns '[x]' square('x', close=')') # returns '[x)' square('y') # returns '[y]' square.keywords # returns {'open': '[', 'close': ']'}
func can be any function, including built-ins like int and maxfunc can itself be a function made by partialFirst solves only, ranked by stars and then time.