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!

1

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.