Monkey patching is a technique used to dynamically update the behavior of a piece of code at run-time. A monkey patch (also spelled monkey-patch, MonkeyPatch) is a way to extend or modify the runtime code of dynamic languages (e.g.
Smalltalk
Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Ka ...
,
JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
,
Objective-C
Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
,
Ruby
A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
,
Perl
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
,
Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
,
Groovy
''Groovy'' (or, less commonly, ''groovie'' or ''groovey'') is a slang colloquialism popular during the 1950s, '60s and '70s. It is roughly synonymous with words such as "excellent", "fashionable", or "amazing", depending on context.
History
The ...
, etc.) without altering the original source code.
Etymology
The term ''monkey patch'' seems to have come from an earlier term, ''guerrilla patch'', which referred to changing code sneakily – and possibly incompatibly with other such patches – at runtime. The word ''
guerrilla'', nearly homophonous with ''
gorilla
Gorillas are herbivorous, predominantly ground-dwelling great apes that inhabit the tropical forests of equatorial Africa. The genus ''Gorilla'' is divided into two species: the eastern gorilla and the western gorilla, and either four or fi ...
'', became ''monkey'', possibly to make the patch sound less intimidating.
[
]
An alternative etymology is that it refers to “monkeying about” with the code (messing with it).
Despite the name's suggestion, the "monkey patch" is sometimes the official method of extending a program. For example, web browsers such as
Firefox
Mozilla Firefox, or simply Firefox, is a free and open-source web browser developed by the Mozilla Foundation and its subsidiary, the Mozilla Corporation. It uses the Gecko rendering engine to display web pages, which implements current and ...
and
Internet Explorer
Internet Explorer (formerly Microsoft Internet Explorer and Windows Internet Explorer, commonly abbreviated IE or MSIE) is a series of graphical user interface, graphical web browsers developed by Microsoft which was used in the Microsoft Wind ...
used to encourage this, although modern browsers (including Firefox) now have an official extensions system.
Definitions
The definition of the term varies depending upon the community using it. In
Ruby
A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
,
Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
, and many other
dynamic programming language
In computer science, a dynamic programming language is a class of high-level programming languages, which at runtime execute many common programming behaviours that static programming languages perform during compilation. These behaviors cou ...
s, the term ''monkey patch'' only refers to dynamic modifications of a class or module at runtime, motivated by the intent to patch existing third-party code as a workaround to a bug or feature which does not act as desired. Other forms of modifying classes at runtime have different names, based on their different intents. For example, in
Zope
Zope is a family of free and open-source web application servers written in Python, and their associated online community. Zope stands for "Z Object Publishing Environment", and was the first system using the now common object publishing methodol ...
and
Plone
Plone is a free and open source content management system (CMS) built on top of the Zope application server. Plone is positioned as an enterprise CMS and is commonly used for intranets and as part of the web presence of large organizations. Hi ...
, security patches are often delivered using dynamic class modification, but they are called ''hot fixes''.
Applications
Monkey patching is used to:
*Replace
methods
Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to:
*Scien ...
/
classes /
attributes
Attribute may refer to:
* Attribute (philosophy), an extrinsic property of an object
* Attribute (research), a characteristic of an object
* Grammatical modifier, in natural languages
* Attribute (computing), a specification that defines a proper ...
/
functions at runtime, e.g. to
stub
Stub or Stubb may refer to:
Shortened objects and entities
* Stub (stock), the portion of a corporation left over after most but not all of it has been bought out or spun out
* Stub, a tree cut and allowed to regrow from the trunk; see Pollardi ...
out a function during testing;
*Modify/extend behaviour of a third-party product without maintaining a private copy of the source code;
*Apply the result of a patch at runtime to the state in
memory
Memory is the faculty of the mind by which data or information is encoded, stored, and retrieved when needed. It is the retention of information over time for the purpose of influencing future action. If past events could not be remembered, ...
, instead of the source code on
disk
Disk or disc may refer to:
* Disk (mathematics), a geometric shape
* Disk storage
Music
* Disc (band), an American experimental music band
* ''Disk'' (album), a 1995 EP by Moby
Other uses
* Disk (functional analysis), a subset of a vector sp ...
;
*Distribute security or behavioural fixes that live alongside the original source code (an example of this would be distributing the fix as a plugin for the
Ruby on Rails
Ruby on Rails (simplified as Rails) is a server-side web application framework written in Ruby under the MIT License. Rails is a model–view–controller (MVC) framework, providing default structures for a database, a web service, and web p ...
platform);
*Explore different automated fixes to provide self-healing.
Pitfalls
Malicious, incompetently written, and/or poorly documented monkey patches can lead to problems:
*They can lead to upgrade problems when the patch makes assumptions about the patched
object
Object may refer to:
General meanings
* Object (philosophy), a thing, being, or concept
** Object (abstract), an object which does not exist at any particular time or place
** Physical object, an identifiable collection of matter
* Goal, an ...
that are no longer true; a new release may very well break the patch. For this reason monkey patches are often made conditional, and only applied if appropriate.
*If two modules attempt to monkey patch the same
method
Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to:
*Scien ...
, one of them (whichever one runs last) "wins" and the other patch has no effect, unless monkey patches are written with a pattern like
alias_method_chain
.
*They create a discrepancy between the original source code and the observed behaviour that can be very confusing to anyone unaware of the existence of the patch. For example, the
Linux
Linux ( or ) is a family of open-source Unix-like operating systems based on the Linux kernel, an operating system kernel first released on September 17, 1991, by Linus Torvalds. Linux is typically packaged as a Linux distribution, which ...
kernel detects proprietary and other third-party modules such as the
Nvidia
Nvidia CorporationOfficially written as NVIDIA and stylized in its logo as VIDIA with the lowercase "n" the same height as the uppercase "VIDIA"; formerly stylized as VIDIA with a large italicized lowercase "n" on products from the mid 1990s to ...
driver, which tamper with kernel structures, so that developers will not waste their time trying to debug a problem that they cannot fix.
*They can be written with malicious code in order to attack the main program, or each other. As an example, in 2009, Giorgio Maone, developer of
NoScript
NoScript (or NoScript Security Suite) is a free software extension for Mozilla Firefox, SeaMonkey, other Mozilla-based web browsers and Google Chrome, written and maintained by Giorgio Maone, an Italian software developer and member of the Moz ...
, attacked the
Adblock Plus
Adblock Plus (ABP) is a free and open-source browser extension for content-filtering and ad blocking. It is developed by developer Wladimir Palant's Eyeo GmbH, a German software company. The extension has been released for Mozilla Firefox ( ...
extension for Firefox, adding exceptions so that advertisements on his own websites would work. The offending code also made sure that if the user attempted to remove the exceptions, they would be added again. The spat caused widespread anger, leading to a back and forth war between new adblock rules being pushed to users, followed by Maone sabotaging the new ones, which eventually led to Mozilla stepping in to change policies regarding add-ons.
Examples
The following Python example monkey-patches the value of
Pi from the standard Python math library to make it compliant with the
Indiana Pi Bill
The Indiana Pi Bill is the popular name for bill #246 of the 1897 sitting of the Indiana General Assembly, one of the most notorious attempts to establish mathematical truth by legislative fiat. Despite its name, the main result claimed by the b ...
.
>>> import math
>>> math.pi
3.141592653589793
>>> math.pi = 3.2 # monkey-patch the value of Pi in the math module
>>> math.pi
3.2
RESTART
>>> import math
>>> math.pi
3.141592653589793
>>>
See also
*
Polyfill
*
Aspect-oriented programming
In computing, aspect-oriented programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. It does so by adding behavior to existing code (an advice) ''without'' modifying t ...
*
Category
Category, plural categories, may refer to:
Philosophy and general uses
* Categorization, categories in cognitive science, information science and generally
*Category of being
* ''Categories'' (Aristotle)
*Category (Kant)
*Categories (Peirce)
* ...
in Objective-C
*
Dynamic loading
Dynamic loading is a mechanism by which a computer program can, at run time, load a library (or other binary) into memory, retrieve the addresses of functions and variables contained in the library, execute those functions or access those varia ...
*
Extension method
In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype or a type. Extension methods are features of some object-orie ...
in C#
*
Self-modifying code
In computer science, self-modifying code (SMC) is code that alters its own instructions while it is executing – usually to reduce the instruction path length and improve performance or simply to reduce otherwise repetitively similar code, ...
References
{{DEFAULTSORT:Monkey Patch
Object-oriented programming
Programming constructs