Monkey patch

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, and Lisp 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, became monkey, possibly to make the patch sound less intimidating.[1]

An alternative etymology is that it refers to “monkeying about” with the code (messing with it).[citation needed]

Despite the name's suggestion, the "monkey patch" is sometimes the official method 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 extensions system.[citation needed]

Definitions

The definition of the term varies depending upon the community using it. In Ruby,[2] Python,[3] and many other dynamic programming languages, 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 and Plone, security patches are often delivered using dynamic class modification, but they are called hot fixes.[citation needed]

Applications

Monkey patching is used to:

  • Replace methods / classes / attributes / functions at runtime, e.g. to stub 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, instead of the source code on disk;
  • 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 platform);

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 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.[4]
  • If two modules attempt to monkey patch the same method, 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.[5]
  • 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 kernel detects proprietary and other third-party modules such as the Nvidia driver, which tamper with kernel structures, so that developers will not waste their time trying to debug a problem that they cannot fix.[6]
  • 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, attacked the Adblock Plus 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.[7]

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.

>>> 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

References

  1. ^ "Glossary — Definition of 'Monkey patch'". Plone Content Management System. Archived from the original on 2021-01-22. Retrieved 2021-07-02. when someone created a guerrilla patch very carefully and tried to avoid any battles, they tried to make it sound less forceful by calling it a monkey patch
  2. ^ Nutter, Charles Oliver. "Refining Ruby". Charles Oliver Nutter.
  3. ^ Biswal, Bimal. "Monkey Patching in Python". Software Technology Tips. Mindfire Solutions. Archived from the original on 22 August 2012. Retrieved 9 December 2013.
  4. ^ Zakas, Nicholas C. (2 March 2010). "Maintainable JavaScript: Don't modify objects you don't own - Human Who Codes". Human Who Codes.
  5. ^ "New in Rails: Module#alias_method_chain". Ruby on Rails.
  6. ^ "Tainted kernels — The Linux Kernel documentation". www.kernel.org. Retrieved 2020-07-12.
  7. ^ Paul, Ryan (2009-05-04). "Mozilla ponders policy change after Firefox extension battle". Ars Technica. Retrieved 2020-07-12.

Read other articles:

Artikel ini sebatang kara, artinya tidak ada artikel lain yang memiliki pranala balik ke halaman ini.Bantulah menambah pranala ke artikel ini dari artikel yang berhubungan atau coba peralatan pencari pranala.Tag ini diberikan pada November 2022. Dancing with the BirdsSutradaraHuw CordeyNaratorStephen FryDistributorNetflixTanggal rilis 23 Oktober 2019 (2019-10-23) Durasi51 menitNegaraAmerika SerikatBahasaInggrisDancing with the Birds adalah film dokumenter 2019 yang disutradarai oleh Huw ...

 

 

Artikel ini mengulas pertempuran dalam Perang Seratus Tahun. Untuk pertempuran sebelumnya tahun 732, lihat Pertempuran Tours. Artikel ini sudah memiliki daftar referensi, bacaan terkait, atau pranala luar, tetapi sumbernya belum jelas karena belum menyertakan kutipan pada kalimat. Mohon tingkatkan kualitas artikel ini dengan memasukkan rujukan yang lebih mendetail bila perlu. (Pelajari cara dan kapan saatnya untuk menghapus pesan templat ini) Pertempuran PoitiersBagian dari the Perang Seratus...

 

 

Seri Dragon BallGambar sampul Pertarungan Super.MangaAlbum nomor20EpisodeSaiyan SagaDidahului olehSerangan Bangsa SaiyaDiikuti denganMenuju Planet NamecDiterbitkan di Jepang1984Diterbitkan di Indonesia1993 Pertarungan Super adalah jilid ke-20 manga Dragon Ball. Pada jilid ini, pertarungan dahsyat antara Piccolo beserta penduduk planet Namek lainnya melawan Frieza dan pasukannya. lbsSeri Dragon BallDiterbitkan oleh Elex Media KomputindoGoku dan Kawan-Kawannya • Kemelut Dragon Ball • Tenkai...

2006 single by Monrose ShameSingle by Monrosefrom the album Temptation Released1 December 2006StudioWeryton (Munich, Germany)Length3:29LabelStarwatchWarnerSongwriter(s)Christian BallardTim HawesPete KirtleyAndrew MurrayProducer(s)JiantSnowflakersMonrose singles chronology Shame (2006) Even Heaven Cries (2007) Shame is a song by all-female German pop group Monrose, recorded for the band's debut studio album, Temptation (2006). It was written by Christian Ballard, Tim Hawes, Pete Kirtley and A...

 

 

Yang MuliaErcole ConsalviPrefect of the Congregation for Propagation of the FaithKardinal Ercole Consalvi, karya Sir Thomas Lawrence (1819).Penunjukan23 Maret 1822 (Pro-Prefect)Masa jabatan berakhir24 Januari 1824PendahuluGiovanni Battista QuarantottiPenerusGiulio Maria della SomagliaJabatan lainKardinal-Diaken Santa Maria ad MartyresImamatTahbisan uskup21 Desember 1782Pelantikan kardinal11 Agustis 1800oleh Paus Pius VIIPeringkatKardinal-DiakenInformasi pribadiLahir(1757-06-08)8 Juni 1757Roma...

 

 

American historian and social critic (1946–2022) For other people with similar names, see Michael Davis (disambiguation). Mike DavisBornMichael Ryan Davis(1946-03-10)March 10, 1946Fontana, California, U.S.DiedOctober 25, 2022(2022-10-25) (aged 76)San Diego, California, U.S.Alma materUniversity of California, Los AngelesSchoolCritical geographyMarxismMain interestsUrban geographyEnvironmental economicsMarxismLabor historyPolitical violenceEconomic history Michael Ryan Davis (March ...

Lokasi Skara di Swedia dan Daerah Västra Götaland. Skara (penduduk 10.700) ialah sebuah kota di Swedia barat, di Daerah Vastra Gotaland. Tanpa pandang ukurannya, Skara memiliki sejarah pendidikan Ekklesia. Sekolah tinggi tertua di Swedia Katedralskolan, terletak di kota ini. Artikel bertopik geografi atau tempat Swedia ini adalah sebuah rintisan. Anda dapat membantu Wikipedia dengan mengembangkannya.lbs

 

 

TV series franchise For other uses, see Apprentice (disambiguation). The ApprenticeCreated byMark BurnettOriginal workThe ApprenticeOwnerMGM TelevisionYears2004–presentFilms and televisionTelevision seriesThe Apprentice (independent international versions, see below)MiscellaneousGenreReality talent game showFirst aired8 January 2004; 20 years ago (2004-01-08)DistributorFremantle The Apprentice is a reality talent game show franchise originally aired in 2004 in the United S...

 

 

Sceaux 行政国 フランス地域圏 (Région) イル=ド=フランス地域圏県 (département) オー=ド=セーヌ県郡 (arrondissement) アントニー郡小郡 (canton) 小郡庁所在地INSEEコード 92071郵便番号 92330市長(任期) フィリップ・ローラン(2008年-2014年)自治体間連合 (fr) メトロポール・デュ・グラン・パリ人口動態人口 19,679人(2007年)人口密度 5466人/km2住民の呼称 Scéens地理座標 北緯48度4...

1686 charter for Albany, New York Dongan CharterOpening paragraph of the Dongan CharterRatifiedJuly 25, 1686LocationAlbany County Hall of RecordsAuthor(s)Governor Thomas DonganPurposeIncorporated the City of Albany The Dongan Charter is the 1686 document incorporating Albany, New York, as a city. Albany's charter was issued by Governor Thomas Dongan of the Province of New York, a few months after Governor Dongan issued a similarly worded, but less detailed charter for the city of New York. ...

 

 

Austrian biologist This article is about the biologist. For other uses, see Paul Weiss (disambiguation). Paul Alfred WeissWeiss in 1963Born(1898-03-21)March 21, 1898Vienna, AustriaDiedSeptember 8, 1989(1989-09-08) (aged 91)New York, United StatesCitizenshipUnited StatesAlma materTechnische Hochschule Wien (1922)Known formorphogenesisdevelopmental biologyneurobiologyAwardsNational Medal of Science (1979)Scientific careerFieldsdevelopmental biologyInstitutionsVienna University of...

 

 

River in TurkeyBatman RiverBatman River DamLocationCountryTurkeyPhysical characteristicsMouth  • locationTigris (Dicle)Length115 km (71 mi)[1] The Batman River is a major tributary of the Tigris in southeast Turkey. The region along the Batman River is known for its oil fields. Course The river originates in Turkey's Anti-Taurus Mountains (at the Sason and Genç mountains)[2] and flows approximately from north to south, passing near the city...

Come leggere il tassoboxAscidieVarie specie di AscidiaceaErnst Haeckel,(1904)Classificazione scientificaDominioEukaryota RegnoAnimalia SottoregnoEumetazoa RamoBilateria SuperphylumDeuterostomia PhylumChordata SubphylumTunicata ClasseAscidiaceaBlainville, 1824 Ordini Aplousobranchia Phlebobranchia Stolidobranchia Ascidiacea Blainville, 1824 è una classe del subphylum degli organismi Tunicati. Sono animali marini, sessili, microfagi filtratori, dal corpo a forma di otre. Indice 1 Descrizione 2...

 

 

Đường Hi Tông唐僖宗Hoàng đế Trung Hoa (chi tiết...)Hoàng đế Đại ĐườngTại vị16 tháng 8 năm 873 - 20 tháng 4 năm 888(14 năm, 248 ngày)Tiền nhiệmĐường Ý TôngKế nhiệmĐường Chiêu TôngThông tin chungSinh(862-06-08)8 tháng 6, 862[1][2]Mất20 tháng 4, 888(888-04-20) (25 tuổi)[1][2]An tángTĩnh lăng (靖陵)Hậu duệ Hậu duệ xem văn bản Tên đầy đủKị húy: Lý Huyên (李儇)B...

 

 

Disambiguazione – Se stai cercando altri significati, vedi Bramante (disambigua). Donato Bramante Sovrintendente Generale delle Fabbriche PapaliDurata mandato1503 –11 aprile 1514 MonarcaGiulio II Leone X Predecessorecarica istituita Donato Donnino di Angelo di Pascuccio, detto il Bramante e conosciuto anche come Donato Bramante (Fermignano, 1444[1] – Roma, 11 aprile 1514[2]), è stato un architetto e pittore italiano, tra i maggiori artisti del Rinasciment...

Michael MandibergThông tin cá nhânSinhNgày sinh22 tháng 12, 1977 (46 tuổi)Nơi sinhDetroit, Michigan Nơi cư trúDetroitGiới tínhphi nhị nguyên giớiQuốc tịchMỹNghề nghiệpnghệ sĩ, lập trình viên, nhà nghiên cứu, họa sĩĐào tạoĐại học Brown, Trường Thiết kế Rhode Island, MFA Viện Nghệ thuật CaliforniaLĩnh vựcNghệ thuật InternetSự nghiệp nghệ thuậtĐào tạoViện nghệ thuật California, Đại học BrownTác p...

 

 

يو بي-56   الجنسية  الإمبراطورية الألمانية الشركة الصانعة كونيغليش فيرفت دانزيغ  المالك البحرية الإمبراطورية الألمانية المشغل البحرية الإمبراطورية الألمانية  المشغلون الحاليون وسيط property غير متوفر. المشغلون السابقون وسيط property غير متوفر. التكلفة وسيط property غير مت...

 

 

Cet article est une ébauche concernant une commune de l’Allier. Vous pouvez partager vos connaissances en l’améliorant (comment ?). Le bandeau {{ébauche}} peut être enlevé et l’article évalué comme étant au stade « Bon début » quand il comporte assez de renseignements encyclopédiques concernant la commune. Si vous avez un doute, l’atelier de lecture du projet Communes de France est à votre disposition pour vous aider. Consultez également la page d’aide ...

Сатым Улуг-Зодатадж. Сотим Улуғзода Дата рождения 11 сентября 1911(1911-09-11) Место рождения кишлак Варзык, Наманганский уезд, Ферганская область, Российская империя Дата смерти 25 июня 1997(1997-06-25) (85 лет) Место смерти Душанбе, Таджикистан Гражданство  Российская империя СССР&...

 

 

  لمعانٍ أخرى، طالع ريبيكا (توضيح). ريبيكا   الإحداثيات 31°48′28″N 83°29′16″W / 31.8078°N 83.4878°W / 31.8078; -83.4878   [1] تقسيم إداري  البلد الولايات المتحدة[2]  التقسيم الأعلى مقاطعة تورنر  خصائص جغرافية  المساحة 2.03472 كيلومتر مربع2.034722 كيلومتر مربع (1 أب�...