Monkey patch

A monkey patch is a way to extend or modify the run-time code of dynamic languages without altering the original source code. This process has also been described as "duck punching".[1]

Contents

Etymology

The term monkey patch seems to have come from an earlier term, guerrilla patch, which referred to changing code sneakily at runtime. The word guerrilla, homophonous with gorilla, became monkey, possibly to make the patch sound less intimidating.[2]

The definition of the term varies depending upon the community using it.

In Python, 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 you desire. Other forms of modifying classes at runtime have different names, based on their different intents. For example, in Zope and Plone, security patches are often delivered using dynamic class modification, but they are called hot fixes.

In Ruby, the term monkey patch means any dynamic modification to a class and is often used as a synonym for dynamically modifying any class at runtime.

Some members in the Ruby world started adopting the term duck punching in lieu of monkey patching, originating from the extensive use of duck typing in Ruby and Python.

Applications

Monkey patching is used to:

Pitfalls

Carelessly written or poorly documented monkey patches can lead to problems:

Even if monkey patching isn't used, some see a problem with the availability of the feature, since the ability to use monkey patching in a programming language is incompatible with enforcing strong encapsulation, as required by the object-capability model, between objects.

See also

References