What is the partialmethod() method in functools module in Python?

Overview

In Python, we use the functools module to create higher-order functions that interact with other functions. The higher-order functions either return other functions or operate on them to broaden the function’s scope without modifying or explicitly defining them.

The partialmethod() method is similar to [partial()](https://www.educative.io/shoteditor/4892716999114752. The only difference is that we use it as a method definition in class.

Example

Below is an example that uses partialmethod() from the functools module.

from functools import partialmethod
class Switch:
def __init__(self):
self._state = False
def set_new_state(self, new_state: bool):
self._state = new_state
@property
def state(self):
return self._state
turn_on = partialmethod(set_new_state, True)
turn_off = partialmethod(set_new_state, False)
switch = Switch()
print("Turning on the switch: ", end="")
switch.turn_on()
print(switch.state)
print("Turning off the switch: ", end="")
switch.turn_off()
print(switch.state)

Explanation

  • Line 1: We will import the partialmethod from the functools module.
  • Line 3: We define a Switch class that contains _state as the attribute.
  • Lines 5–6: We define the __init__ method, which sets the _state attribute to False by default when a new instance of Switch is created.
  • Lines 8–9: We define the set_new_state instance method where we can set a new state to the Switch object.
  • Lines 15-16: We will create the two partialmethod descriptors, turn_on and turn_off. These descriptors will internally call the set_new_state() method with True or False. Using these descriptors, we can set the state of the Switch instance.
  • Lines 18-25: An instance of the Switch class is created, and the state is turned on and off using the turn_on and turn_off descriptors.

Free Resources