Python
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.
Exercise 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)).
Show example solution
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))
Test yourself
-
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
Show answer
A new callable with exp bound to 2 — partial returns a new callable; exp=2 is pre-bound and base is given at call time.
-
Complete the partial call
from functools import partial
def power(base, exp):
return base ** exp
cube = ____(power, exp=3)
print(cube(2))
Show answer
from functools import partial
def power(base, exp):
return base ** exp
cube = partial(power, exp=3)
print(cube(2))
-
Match the partial concepts
- partial(power, exp=2)
- exp bound
- square(5)
- base becomes 5
- curry
- Stepwise binding
- square
- New callable
Next lesson: functools.reduce