Python partialmethod()

created:

updated:

tags: python

I encountered partialmethod() at work, and I didn’t understand what they were so I looked it up.

functools

partialmethod() comes from functools builtin library. “The functools module is for higher-order functions: functions that act on or return other functions. In general, any callable object can be treated as a function for the purposes of this module.”

partialmethod()

“Return a new partialmethod descriptor which behaves like partial except that it is designed to be used as a method definition rather than being directly called.”

# partialmethod() signature
functools.partialmethod(func, /, *args, **keywords)
# func must be a descriptor or a callable
# if descriptor:
# - calls to `__get__` are delegated to the underlying descriptor and
#   an appropriate partial object returned as the result.
# if non-descriptor callable:
# - an appropriate bound method is created dynamically. This behaves like
#   a normal Python function when used as a method: the `self` argument
#   will be inserted as the first positional argument, even before the
#   `args` and `keywords` supplied to the `partialmethod` constructor.

Example

from functools import partialmethod

class Cell:
    def __init__(self):
        self._alive = False

    @property
    def alive(self):
        return self._alive

    def set_state(self, state):
        self._alive = bool(state)
    set_alive = partialmethod(set_state, True)
    set_dead = partialmethod(set_state, False)

>>> c = Cell()
>>> c.alive
False
>>> c.set_alive()
>>> c.alive
True

References