Monkey-patching is the technique of swapping functions or methods with others in order to change a module, library or class behavior.
There are some people with strong opinions about it. I haven’t, but it comes really useful when testing, to simulate side-effecting functions or to silence expected errors and warnings.
Class methods monkey patching in Python is really easy, as you can freely assign function to class method names:
This way all the instances of the target class will have the method monkey-patched and there is no problem with arguments, bindings… Everything really straight-forward.
Mar 11, 2015 Safely applying monkey patches in Python. That is, whether the decorator was applied to a class, a function or static method, a class method or an instance method. If one of the mock.patch methods is used with autospec=True on a staticmethod in an. Hi, I hit this problem wile mocking one static method and found.
We can also call the old existing method, to handle only some cases or to add some functionality while not repeating code (DRY):
But what if we wanted to do the same, patching just a single instance?
To recap, the requirements are:
- we want just the current instance to be patched;
- we want to build something on top of the existing method, not to replace it entirely;
- we want each monkey-patch not to rollback all the previous ones (so no
super()
or class method call); - we want to be able to do so also from inside a method.
The trick is to save and use the existing method as we did above, and then bind the new function to the instance with types.MethodType
before assigning it to the method name.
The binding is the magic that causes the instance to be passed as first argument (self
) each time the method is called. See thesetwo StackOverflow questions to get an idea.
And here we go!
Tactical Trunk Monkey Patch
A practical example
Python Monkey Patch Static Method Pdf
You can see this technique being used in youtube-dl to silence expected warnings in this commit.
Python Static Method
The monkey-patching of the instance is done on itself by a method of a testing subclass of the downloader.