Python Monkey Patch Property
Hi, is there some well-known problems with class method monkeypatching?I've got this error message:unbound method getpocetneocislovanych must be called with Pozemokinstance as first argument (got Subjekt instance instead)The method is declared as:@classmethod@monkeypatch(Dokument)def getpocetneocislovanych(cls, subjekt):?? Return cls.objects.filter(subjekt = subjekt, cisloisnull =True).count # or pass, this line is not importantand the monkey patch decorator is declared as:def monkeypatch(cls):?? Def decorator(func):???? Setattr(cls, func.name, func)???? Return func?? Return decoratorThe decorators are applied in order.
So you first add the yetundecorated function as an attribute of the class, then pass thefunction to classmethod.FWIW, this monkeypatch decorator is IMHO a plain waste of time. Thefollowing code does the same thing and is (IMHO again).much. more readable:def getpocetneocislovanych(cls, subjekt):??? Return cls.objects.filter(?????subjekt=subjekt,?????cisloisnull= True?????).count # or pass, this line is not importantDokument.getpocetneocislovanych=@classmethod(getpocetneocislovanych)Also, Django's BestPractice(tm) is to define such 'query' methods on the? Model's manager, not as a classmethod of the model.My 2 centsthx, I changed my definitions to manager style and have no moreproblemsseems to be safe to use manager instead classmethod - do not knowwhy:-).
Iron On Monkey Patch
Monkey patching a way of programming in which we can modify or extend the executing code at runtime. This is offered in some dynamic typing languages like javascript, perl, python etc. This can be scary in a production environment because it is very difficult to debug this kind of code, but this can be very useful in some situation like testing. We are going through an issue that is happening in a server deployment, but that is working fine in the dev environment. Moreover we can’t put the source code there and debug or put some break point and watch different variables, because the libraries are proprietary, so in this situation monkey patching is to our rescue, we can add some logging dynamically to the source code and track what is going on.
How to do monkey patching in python, lets say we have a class Foo with bar method in it in module baz.class Foo(object):def bar(self):bar bodyNow from outside, I can define a function monkeybardef monkeybar(self):monkeybar bodyNow I can modify the content of bar dynamically and run as below:import bazbaz.Foo.bar = monkeybarnewobj = baz.Foonewobj.barThere is a saying in python world about the dynamic typing/ duck typing “If it walks like a duck and quacks like a duck, it is a duck”. With this we can say “Go on puching until it walks and quacks like a duck:)”.