Skip to content

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

  1. functools.partial
  2. Partial vs closure
  3. partialmethod — for classes
  4. Inspection
  5. 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
int_from_hex = partial(int, base=16)
int_from_hex("ff")   # 255

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#

  1. What do partial.func, .args, .keywords expose?
  2. When is partial better than a lambda?
  3. How does partialmethod differ from partial?

What's next#

Topic Page
Closures Closures
Decorators Decorators
Higher-order functions Higher Order Functions