Wednesday, April 26, 2017

Monkey patch an instance method in Python3

import types

class SomeClass(object):
    def __init__(self, x):
        self.x = x
    def some_method(self, y):
        print("Original method", self.x + y)

# creates instance
instance = SomeClass(1)

# test instance's method
instance.some_method(1)

>>> Original method 2

# The method to patch
def new_method(self, y):
    print("New method", self.x * y)

# monkeypatch using types.MethodType()
instance.some_method = types.MethodType(new_method, instance)

# test patched method
instance.some_method(10)
>>> New method 10

No comments: