Search code examples
pythonpython-decoratorsmonkeypatching

Dynamically monkey patch a python 2.7 class


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)

Solution

  • 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))