CodeBlanks Logo Icon CodeBlanks

functools.partial

Learn partial application with functools.partial.

functools.partial

functools.partial pre-binds some arguments of a function and returns a new callable. The technique is called currying or partial application.

For example, given def power(base, exp):, writing square = partial(power, exp=2) makes square(5) mean power(5, exp=2).

from functools import partial

def power(base, exp):
    return base ** exp

square = partial(power, exp=2)
print(square(5))  # 25

Unbound arguments are passed at call time; bound ones stay fixed.

Configuration with partial

partial is handy for creating ready-to-use callables with fixed settings. For example, if a log function has signature log(level, message), then info = partial(log, level="INFO") gives you a short callable that takes only the message.

This offers light customization without writing a class. Calling info("server started") means log("INFO", "server started").

Positional and keyword arguments can be bound together; the rest are passed at call time.

Practice Square and cube functions with partial

The function power(base, exp) returns base ** exp. Use partial to build two callables: square (exp=2) and cube (exp=3). Print the results with print(square(5)) and print(cube(2)).

Starter code

main.py
from functools import partial

# power takes base and exponent; return the power result
# build square and cube by binding the exponent with partial
# print both results

Sample solution

main.py
from functools import partial

def power(base, exp):
    return base ** exp

square = partial(power, exp=2)
cube = partial(power, exp=3)
print(square(5))
print(cube(2))

Expected output

25
8

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does partial(power, exp=2) return?

  • The result of calling power(2)
  • The power function itself
  • 2 raised to the base value
  • A new callable with exp bound to 2 Correct answer

Explanation: partial returns a new callable; exp=2 is pre-bound and base is given at call time.

2 Complete the partial call

Question
from functools import partial

def power(base, exp):
    return base ** exp

cube = ____(power, exp=3)
print(cube(2))
Answer
from functools import partial

def power(base, exp):
    return base ** exp

cube = partial(power, exp=3)
print(cube(2))

Explanation: partial(power, exp=3) makes cube a callable with exponent 3.

3 Match the partial concepts

Term Meaning
partial(power, exp=2) exp bound
square(5) base becomes 5
curry Stepwise binding
square New callable

All lessons in Advanced