views:

86

answers:

2

If I'm using a module/class I have no control over, how would I decorate one of the methods?

I understand I can: my_decorate_method(target_method)() but I'm looking to have this happen wherever target_method is called without having to do a search/replace.

Is it even possible?

A: 

Yes it's possible, but there are several problems. First whet you get method from class in obvious way you get a warper object but not the function itself.

class X(object):
    def m(self,x):
        print x

print X.m           #>>> <unbound method X.m>
print vars(X)['m']  #>>> <function m at 0x9e17e64>

def increase_decorator(function):
    return lambda self,x: function(self,x+1)

Second I don't know if settings new method will always work:

x = X()
x.m(1)         #>>> 1
X.m = increase_decorator( vars(X)['m'] )
x.m(1)         #>>> 2
lionbest
+2  A: 

Don't do this.

Use inheritance.

import some_module

class MyVersionOfAClass( some_module.AClass ):
    def someMethod( self, *args, **kwargs ):
        # do your "decoration" here.
        super( MyVersionOfAClass, self ). someMethod( *args, **kwargs )
        # you can also do "decoration" here.

Now, fix you main program to use MyVersionOfAClass instead of some_module.AClass.

S.Lott
That was the original way I looked at the problem but it was a lot of work. The method in the accepted answer is useful to know - even if it isn't the most correct way to do things.
digitala
It's not a matter of "more correct" as much as a matter of "readable" and "maintainable". Your use case is the *exact* reason that OO languages have inheritance. It may appear as a lot of work, but it is what every other programmer expects to see. In the long run, funny dynamic decorators are a liability. Plain old inheritance will not become a liability.
S.Lott