Search code examples
pythonmonkeypatching

Can I dynamically modify (monkey patch) an existing python class method to add a decorator


Let's say I have an existing python 2.7 class:

class TestClass(object):
    def foo1(self):
        return self.foo2()

    def foo2(self):
        return self.foo3()

    def foo3(self):
        return 'Hello World!'

Is there a way during runtime to dynamically add (monkey patch) a decorator (@testdecorator) to each of the three existing methods, foo1, foo2, and foo3?

Thank you in advance for any suggestions!


Solution

  • That sounds like a horrible thing to do, but it's perfectly possible. @decorator is just syntactic sugar; you can do it the long way:

    TestClass.foo1 = testdecorator(TestClass.foo1)