Skip to content

Instantly share code, notes, and snippets.

@cgoldberg
Created August 20, 2025 18:34
Show Gist options
  • Save cgoldberg/57d6d438b463840c3a97d4d5dca3b9df to your computer and use it in GitHub Desktop.
Save cgoldberg/57d6d438b463840c3a97d4d5dca3b9df to your computer and use it in GitHub Desktop.
Python - monkeypatch a method on a class and call the original method from the new one
#!/usr/bin/env python
#
# monkeypatch a method on a class and call the original method from the new one
from functools import partialmethod
class MyClass:
# this is the original method
def my_method(self):
print("hello from the original method")
# this is a function that replaces the original method
def my_method(self, orig):
print("hello from the replacement method")
# orig here is the original method, so can be called like this:
orig(self)
# this makes the function a method on the class
MyClass.my_method = partialmethod(my_method, MyClass.my_method)
# example usage
if __name__ == "__main__":
foo = MyClass()
foo.my_method()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment