0

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!

mba12
  • 2,702
  • 6
  • 37
  • 56
  • Also might be useful for you: http://stackoverflow.com/questions/6098073/creating-a-function-object-from-a-string – Torxed Mar 08 '16 at 17:30

2 Answers2

3

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)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
1

Yes:

TestClass.foo1 = testdecorator(TestClass.foo1)

And so on.

If you want to patch it on specific instances rather than on the class, that is doable too, although it's a little more work.

kindall
  • 178,883
  • 35
  • 278
  • 309