1

Wondering if anyone has a good way to dynamically inspect a class for its function types and then dynamically monkey patch a decorator onto some of those functions.

I'm trying this but not getting the results I expect. Walking through the methods in the class seems to be working but doing the monkey patch itself seems to fail.

def decorator(callable):
    pass

class Test(object):
    def foo1(self):
        return self.bar()

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

    def foo3(self):
        return 0

for x,y in Test.__dict__.items():
        if type(y) == FunctionType:
            Test.x = decorator(Test.x)
1
  • 1
    This approach of adding a decorator dynamically is totally valid. I would also prefer a better syntax by Python but for the moment it should be fine. Commented Mar 8, 2016 at 20:13

1 Answer 1

4

Of course Test.x does not exist and this will raise AttributeError. You can use setattr for this. Also x.__dict__ looks ugly to me, I'd use vars(x) instead.

for x,y in vars(Test).items():
    if type(y) == FunctionType:
        setattr(Test, x, decorator(y))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.