Partial Functions#
Partial application fixes some arguments of a function, producing a new callable with fewer parameters. Python provides functools.partial and partialmethod for this pattern.
How to use this page
Alternative to small closures and lambdas. See Closures, Higher Order Functions.
At a glance
| Track | Python Advanced → Advanced Functions |
| Sections | 5 major topics |
| Outline | Use the right-hand TOC to jump |
Topics: functools.partial · Partial vs closure · partialmethod — for classes · Inspection · Use cases
functools.partial- Partial vs closure
partialmethod— for classes- Inspection
- Use cases
functools.partial#
from functools import partial
def power(base, exp):
return base ** exp
square = partial(power, exp=2)
square(5) # 25
cube = partial(power, exp=3)
cube(2) # 8
| Call form | Meaning |
|---|---|
partial(fn, a) |
Fix first positional |
partial(fn, key=val) |
Fix keyword |
partial(fn, a, key=val) |
Mix |
Partial vs closure#
# partial
double = partial(pow, 2) # WRONG: pow(2, x) — base fixed at 2
# correct power partial
def power(base, exp):
return base ** exp
square = partial(power, exp=2)
square(5) # 25
# closure equivalent
def make_square():
def square(x):
return power(x, 2)
return square
Partial is clearer when fixing arguments of an existing function; closures when adding logic.
partialmethod — for classes#
from functools import partialmethod
class Cell:
def set_value(self, value):
self.value = value
set_zero = partialmethod(set_value, 0)
set_one = partialmethod(set_value, 1)
Binds like partial but produces a descriptor for methods.
Inspection#
from functools import partial
f = partial(power, exp=2)
f.func # original function
f.args # ()
f.keywords # {'exp': 2}
Use cases#
| Scenario | Example |
|---|---|
| Configure callbacks | partial(handler, user_id=42) |
| Pre-fill API calls | partial(requests.get, timeout=5) |
| Bind sort keys | Rare — prefer key=lambda or itemgetter |
| Currying style | partial(add, 1) then call with second arg |
True currying (unary chain) is not native — partial covers most needs.
Interview traps (quick reference)#
| Trap | What goes wrong | Safe approach |
|---|---|---|
Wrong arg order in partial(pow, 2) |
Fixes base not exp | Use keywords |
| Mutable partial kwargs | Shared state | Immutable defaults |
| Partial vs decorator confusion | Different purposes | Partial pre-fills args |
Mental model checklist#
- What do
partial.func,.args,.keywordsexpose? - When is partial better than a lambda?
- How does
partialmethoddiffer frompartial?
What's next#
| Topic | Page |
|---|---|
| Closures | Closures |
| Decorators | Decorators |
| Higher-order functions | Higher Order Functions |