[Tutor] monkey patching question

Albert-Jan Roskam fomcl at yahoo.com
Wed Feb 18 12:15:40 CET 2015



----- Original Message -----

> From: Dave Angel <davea at davea.name>
> To: tutor at python.org
> Cc: 
> Sent: Tuesday, February 17, 2015 11:50 PM
> Subject: Re: [Tutor] monkey patching question
> 
> On 02/17/2015 04:53 PM, Albert-Jan Roskam wrote:
>>  Hi,
>> 
>>  I would like to monkey patch a function 'decode' that is defined 
> inside a class. It is defined there because it is a logical place, next to its 
> counterpart *method* 'encode'. I can successfully monkey patch meth1, 
> but when I call meth2, it does not use the patched decorator. How can this be 
> done? In this example, I would like to effectively "turn off" @decode. 
> I am hoping for a solution that works on Python 2.7 and 3.3+.
>> 
>> 
>>  import inspect, functools
>>  class Foo(object):
>> 
>>       def decode(func):
>>           @functools.wraps(func)
>>           def wrapped(*args, **kwargs):
>>               print "original decorator was called"
>>               return func(*args, **kwargs).decode("utf-8")
>>           return wrapped
>> 
>>       def encode(self):
>>           """this is just here to show why decode() is 
> defined
>>           within Foo"""
>>           pass
>> 
>>       def meth1(self):
>>           return "original method was called"
>> 
>>       @decode
>>       def meth2(self):
>>           return b"python rocks"
>> 
> 
> I assume the monkey patching happens in some other file which will 
> import this one.
> 
> So by the time the import is finished, the meth2() method has already 
> been decorated by the decode function.
> 
> 


<snip>


Hi Dave, Danny, 


aha, now I see why it does not work. The code is patched, but it's too little, too late. 


>> 
>>  original decorator was called
>>  u'python rocks' <type 'unicode'>
> 
> 
> I think you're going to have to patch meth2().  Patching decode won't 
> help, since it's already done its work.


But in reality there is meth2 through methn, where n is at least a dozen. I considered monkey patching because it seemed easy to experiment with and the use case for which this would be needed was not very common. And it's fun to experiment with it of course. But I will have to refactor my decode decorator. Thanks!!

Albert-Jan


More information about the Tutor mailing list