Lecture
In computer programming, monkey patching is a technique used to dynamically update the behavior of a piece of code at run time. It is used to extend or modify the runtime code of dynamic languages (such as Smalltalk, JavaScript, Objective-C, Ruby, Perl, Python, Groovy, etc.) without altering the original source code.
The term «monkey patch» appears to have come from an earlier term, «guerrilla patch», which referred to changing code stealthily – and possibly incompatibly with other such patches – at run time. The word «guerrilla», almost a homophone of «gorilla», became «monkey», possibly to make the patch sound less intimidating.
An alternative etymology is that the word refers to «monkeying about» with the code (messing around with it).
Despite the name, monkey patching is sometimes an official way of extending a program. For example, web browsers such as Firefox and Internet Explorer used to encourage this, although modern browsers (including Firefox) now have an official extension system.
The definition of the term varies depending on the community using it. In Ruby,, Python and many other dynamic programming languages, the term «monkey patch» refers only to dynamic modifications of a class or module at run time, motivated by the intent to patch existing third-party code as a workaround for a bug or a feature that does not behave as desired. Other forms of modifying classes at run time have different names, depending on their different purposes. For example, in Zope and Plone, security patches are often delivered using dynamic class modification, but they are called hot fixes.
Malicious, incompetently written and/or poorly documented monkey patches can lead to problems:
alias_method_chain. The following Python example adjusts the value of pi from Python's standard math library so that it conforms to the Indiana Pi Bill.
>>> import math >>> math.pi 3.141592653589793 >>> math.pi = 3.2 # monkey-patch the value of Pi in the math module >>> math.pi 3.2
Let's look at how you can build an interceptor for the Fetch API using monkey patching in JavaScript:
const { fetch: originalFetch } = window;
window.fetch = async (...args) => {
let [resource, config ] = args;
// request interceptor here
const response = await originalFetch(resource, config);
// response interceptor here
return response;
};
Comments