[Python-Dev] Monkeypatching idioms -- elegant or ugly?

Steve Holden steve at holdenweb.com
Tue Jan 15 17:17:02 CET 2008


glyph at divmod.com wrote:
> On 03:37 pm, guido at python.org wrote:
>> I think it's useful to share these recipes, if only to to establish
>> whether they have been discovered before, or to decide whether they
>> are worthy of a place in the standard library. I didn't find any
>> relevant hits on the ASPN Python cookbook.
> 
>>from <somewhere> import <someclass>
>> class <newclass>(<someclass>):
>>    __metaclass__ = monkeypatch_class
>>    def <method1>(...): ...
>>    def <method2>(...): ...
>>    ...
> 
> I've expressed this one before as "class someclass(reopen(someclass)):", 
> but have thankfully never needed to actually use that in a real program. 
> It's been a helpful tool in explaining to overzealous Ruby-ists that 
> "reopenable" classes are not as unique as they think.
> 
> My feelings on monkeypatching is that it *should* feel a little gross 
> when you have to do it, so the code I've written that does 
> monkeypatching for real is generally a bit ugly.

Yes, monkeypatching should never be formalized to the point where 
novices see it as other than a tool of last resort. Otherwise a user 
base will grow that uses monkeypatching instead of subclassing, for 
example (shudder).

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/



More information about the Python-Dev mailing list