I've been surfing the internet and I can't figure out what Monkey paching is .
At first I thought it was exclusive to the language Python
, but it seems that it is not so and I had never heard this term before.
As far as I can tell it looks like a way to overwrite code, but I haven't understood it very well.
Can someone explain to me what Monkey Patching is? How is it used and what applications does it have?
"Monkey Patching" is a term not only used in Python, it is also used in other programming languages like
JavaScript
,Ruby
, etc.Which means that we can make modifications in our code to classes and modules that have been previously defined, at runtime .
Its use and its applications are varied, but basically what it allows you to do is add existing functionality to classes and other modules that may be useful for the project you are developing, without having to modify said module.
For this it is necessary that the language we are using is dynamic . To understand it well, I'm going to put the answer in language agnostic and in Python.
language agnostic
I think the best way to explain it is with an example. Suppose I define a called class
Persona
that only has the methodinformación
:This class
Persona
is in a module, and I need the person to be able to say hello. By applying Monkey Patching I can redefine the classPersona
in my own script, creating the greeting.In this way, the class
Persona
will be able to say hello, despite the fact that this is not defined in the place where the person is .Departure
Emphasize that
Persona
the method has not been injected in the module that is foundsaludo
. This module is still intact and people only have the possibility to say hello in our script.in python
For the Python example, we can choose any class already created in one of its libraries, for example I am going to use the fractions library and its class
Fraction
and I am going to query an attribute:Departure:
As we can see the class
Fraction
does not have the attributedevuelve_cuatro
so it gives us an error, but I can define it using Monkey PatchingDeparture:
4
Here we have created the object
f2_5
that already has the attributedevuelve_cuatro
Obviously this example is quite silly, nobody is going to want to do this, but for example it would be interesting through Monkey Patching to implement in the class
Fractión
, a method that tells us if the fraction is an integer or not, let's do it:Departure:
In the specific case of Python, there is an exception for built-in modules that are written in
C
(for example ) and Monkey Patchingrandom
cannot be applied to these, but everything written in pure Python can.