Movatterモバイル変換
[0]ホーム
[Python-ideas] Fwd: Define a method or function attributeoutside of a class with the dot operator
Steven D'Apranosteve at pearwood.info
Sat Feb 11 23:10:52 EST 2017
On Fri, Feb 10, 2017 at 06:17:54PM +0200, Markus Meskanen wrote:> Well yes, but I think you're a bit too fast on labeling it a mistake to use> monkey patching...More importantly, I think we're being a bit too quick to label this technique "monkey-patching" at all. Monkey-patching (or MP for brevity) implies making modifications to some arbitrary *uncooperative* class (or instance). When you're plugging electrodes into a monkey's brain, the monkey has no say in it.This proposed syntax can, of course, be used that way, but Python is already a "consenting adults" language and already has setattr:setattr(some_class, 'get_shrubbery', get_shrubbery)which is all you need to enable MP for good or evil.There have been a few times where I would have used this syntax if it had been available, and none of them were MP. They were injecting methods into classes I controlled.I suspect that this technique wouldn't feel so bad if we had a proper, respectable sounding "design pattern" name for it, like "method injection" or something. I expect that the only reason there is no name for this is that Java doesn't allow it. (I think.) So I'm going to call it "method injection".I don't think there's any evidence that slightly cleaner syntax for method injection will encourage MP. We already have clean syntax to inject arbitrary attributes (including methods made with lambda):TheClass.method = lambda self: ...and I don't think there's an epidemic of MP going on.-- Steve
More information about the Python-ideasmailing list
[8]ページ先頭