Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

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

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

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)
Example of partialmethod() from functools

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.

RELATED TAGS

python
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring