Editor

Build Your Own partial

#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:

  • the stored args first, then more_args, and
  • the stored kwargs 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).

Examples

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': ']'}

Constraints

  • func can be any function, including built-ins like int and max
  • func can itself be a function made by partial

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.