Prohaska Stack 🚀

When monkey patching an instance method can you call the overridden method from the new implementation

April 10, 2025

đź“‚ Categories: Ruby
🏷 Tags: Monkeypatching
When monkey patching an instance method can you call the overridden method from the new implementation

Monkey patching successful Python, a almighty but generally arguable method, permits you to modify current codification astatine runtime. This tin beryllium extremely utile for fixing bugs, including options, oregon equal customizing 3rd-organization libraries with out straight altering their origin codification. A communal motion that arises once monkey patching case strategies is whether or not you tin inactive entree the first, overridden technique from inside the fresh implementation. The reply is a resounding sure, and knowing however to bash truthful opens ahead a planet of versatile and elegant coding potentialities.

Preserving First Performance

Calling the overridden technique is important for sustaining anticipated behaviour piece extending oregon modifying performance. It permits your spot to physique upon the current codification instead than wholly changing it. This attack is peculiarly utile once you lone demand to set a tiny facet of the first technique’s behaviour.

Ideate, for case, you’re running with a room that has a logging relation. You privation to adhd a timestamp to all log communication. Alternatively of rewriting the full logging methodology, you tin monkey spot it to call the first technique and past prepend the timestamp to its output.

This pattern importantly reduces codification duplication and minimizes the hazard of introducing fresh bugs by preserving the center logic of the first technique.

Methods for Calling Overridden Strategies

Location are respective methods to accomplish this. 1 communal attack entails storing a mention to the first technique earlier monkey patching. This mention tin past beryllium known as inside the fresh implementation.

  • Shop a mention to the first technique.
  • Call the first methodology inside the fresh implementation.

Present’s a elemental illustration:

people MyClass: def original_method(same): mark("First methodology") original_method = MyClass.original_method def patched_method(same): mark("Earlier calling first") original_method(same) mark("Last calling first") MyClass.original_method = patched_method case = MyClass() case.original_method() Output: Earlier calling first, First technique, Last calling first 

Different method entails utilizing the __wrapped__ property, though this is little communal and depends connected however the monkey patching is carried out. Any decorators oregon monkey patching libraries make the most of __wrapped__ to shop the first relation.

Applicable Examples and Usage Instances

See a script wherever you’re utilizing a 3rd-organization room for information processing, however its mistake dealing with is inadequate. You may monkey spot the room’s information processing methodology to see much strong mistake dealing with, piece inactive calling the first methodology to execute the center information processing duties.

Different illustration entails including instrumentation oregon profiling to current strategies. By monkey patching, you tin easy path the execution clip of a methodology with out modifying its center performance. You would call the first technique inside the patched interpretation, measuring the clip earlier and last its execution.

Fto’s opportunity you are running with a net model, and you privation to adhd caching to circumstantial API calls. Monkey patching permits you to intercept the API call, cheque the cache, and both instrument the cached consequence oregon call the first API methodology and past cache the consequence.

Possible Pitfalls and Champion Practices

Piece almighty, monkey patching ought to beryllium utilized judiciously. Overusing it tin brand your codification more durable to realize and debug. It’s crucial to intelligibly papers immoderate monkey patching you bash and to beryllium alert of possible conflicts with another libraries oregon codification modifications. Prioritize focused and fine-documented adjustments to reduce unintended broadside results. Investigating is important to guarantee the patched codification behaves arsenic anticipated and doesn’t present fresh bugs.

  1. Papers your monkey patches intelligibly.
  2. Trial completely last implementing monkey patches.
  3. Usage monkey patching sparingly and lone once essential.

Selecting descriptive names for your patched strategies and variables improves readability and reduces disorder. Moreover, beryllium conscious of possible conflicts. If aggregate patches mark the aforesaid methodology, the command successful which they are utilized issues. Cautious readying and execution are indispensable for palmy monkey patching.

Larn much astir precocious Python strategies. [Infographic astir monkey patching champion practices]

Often Requested Questions

Q: What are the alternate options to monkey patching?

A: Alternate options see utilizing decorators, subclassing, and dependency injection. These approaches tin message much construction and maintainability, peculiarly successful bigger tasks.

Q: Tin monkey patching beryllium utilized successful exhibition codification?

A: Piece imaginable, usage monkey patching successful exhibition with utmost warning. Thorough investigating and cautious information of possible dangers are paramount.

Monkey patching gives a almighty mechanics for modifying present codification behaviour, particularly once nonstop codification adjustments are not possible. Knowing however to call the first methodology inside the patched implementation permits for much seamless and managed modifications. By pursuing champion practices, documenting totally, and investigating rigorously, builders tin leverage the flexibility of monkey patching piece mitigating its inherent dangers. Using alternate approaches similar decorators and subclassing tin message much structured options relying connected the discourse and complexity of the task. By cautiously contemplating these facets, builders tin efficaciously usage monkey patching to heighten and accommodate their codification arsenic wanted. Larn much astir monkey patching. Research Python champion practices. Dive into package investigating methodologies. Research additional and detect however monkey patching tin heighten your Python improvement workflow.

Question & Answer :
Opportunity I americium monkey patching a technique successful a people, however might I call the overridden technique from the overriding methodology? I.e. Thing a spot similar ace

E.g.

people Foo def barroom() "Hullo" extremity extremity people Foo def barroom() ace() + " Planet" extremity extremity >> Foo.fresh.barroom == "Hullo Planet" 

EDIT: It has been 9 years since I primitively wrote this reply, and it deserves any beauty room to support it actual.

You tin seat the past interpretation earlier the edit present.


You tin’t call the overwritten technique by sanction oregon key phrase. That’s 1 of the galore causes wherefore monkey patching ought to beryllium prevented and inheritance beryllium most popular alternatively, since evidently you tin call the overridden technique.

Avoiding Monkey Patching

Inheritance

Truthful, if astatine each imaginable, you ought to like thing similar this:

people Foo def barroom 'Hullo' extremity extremity people ExtendedFoo < Foo def barroom ace + ' Planet' extremity extremity ExtendedFoo.fresh.barroom # => 'Hullo Planet' 

This plant, if you power instauration of the Foo objects. Conscionable alteration all spot which creates a Foo to alternatively make an ExtendedFoo. This plant equal amended if you usage the Dependency Injection Plan Form, the Mill Methodology Plan Form, the Summary Mill Plan Form oregon thing on these traces, due to the fact that successful that lawsuit, location is lone spot you demand to alteration.

Delegation

If you bash not power instauration of the Foo objects, for illustration due to the fact that they are created by a model that is extracurricular of your power (similar ruby-connected-rails for illustration), past you may usage the Wrapper Plan Form:

necessitate 'delegate' people Foo def barroom 'Hullo' extremity extremity people WrappedFoo < DelegateClass(Foo) def initialize(wrapped_foo) ace extremity def barroom ace + ' Planet' extremity extremity foo = Foo.fresh # this is not really successful your codification, it comes from location other wrapped_foo = WrappedFoo.fresh(foo) # this is nether your power wrapped_foo.barroom # => 'Hullo Planet' 

Fundamentally, astatine the bound of the scheme, wherever the Foo entity comes into your codification, you wrapper it into different entity, and past usage that entity alternatively of the first 1 everyplace other successful your codification.

This makes use of the Entity#DelegateClass helper technique from the delegate room successful the stdlib.

“Cleanable” Monkey Patching

Module#prepend: Mixin Prepending

The 2 strategies supra necessitate altering the scheme to debar monkey patching. This conception reveals the most well-liked and slightest invasive technique of monkey patching, ought to altering the scheme not beryllium an action.

Module#prepend was added to activity much oregon little precisely this usage lawsuit. Module#prepend does the aforesaid happening arsenic Module#see, but it mixes successful the mixin straight beneath the people:

people Foo def barroom 'Hullo' extremity extremity module FooExtensions def barroom ace + ' Planet' extremity extremity people Foo prepend FooExtensions extremity Foo.fresh.barroom # => 'Hullo Planet' 

Line: I besides wrote a small spot astir Module#prepend successful this motion: Ruby module prepend vs derivation

Mixin Inheritance (breached)

I person seen any group attempt (and inquire astir wherefore it doesn’t activity present connected StackOverflow) thing similar this, i.e. seeing a mixin alternatively of prepending it:

people Foo def barroom 'Hullo' extremity extremity module FooExtensions def barroom ace + ' Planet' extremity extremity people Foo see FooExtensions extremity 

Unluckily, that gained’t activity. It’s a bully thought, due to the fact that it makes use of inheritance, which means that you tin usage ace. Nevertheless, Module#see inserts the mixin supra the people successful the inheritance hierarchy, which means that FooExtensions#barroom volition ne\’er beryllium referred to as (and if it have been known as, the ace would not really mention to Foo#barroom however instead to Entity#barroom which doesn’t be), since Foo#barroom volition ever beryllium recovered archetypal.

Technique Wrapping

The large motion is: however tin we clasp connected to the barroom methodology, with out really retaining about an existent technique? The reply lies, arsenic it does truthful frequently, successful useful programming. We acquire a clasp of the methodology arsenic an existent entity, and we usage a closure (i.e. a artifact) to brand certain that we and lone we clasp connected to that entity:

people Foo def barroom 'Hullo' extremity extremity people Foo old_bar = instance_method(:barroom) define_method(:barroom) bash old_bar.hindrance(same).() + ' Planet' extremity extremity Foo.fresh.barroom # => 'Hullo Planet' 

This is precise cleanable: since old_bar is conscionable a section adaptable, it volition spell retired of range astatine the extremity of the people assemblage, and it is intolerable to entree it from anyplace, equal utilizing observation! And since Module#define_method takes a artifact, and blocks adjacent complete their surrounding lexical situation (which is wherefore we are utilizing define_method alternatively of def present), it (and lone it) volition inactive person entree to old_bar, equal last it has gone retired of range.

Abbreviated mentation:

old_bar = instance_method(:barroom) 

Present we are wrapping the barroom methodology into an UnboundMethod methodology entity and assigning it to the section adaptable old_bar. This means, we present person a manner to clasp connected to barroom equal last it has been overwritten.

old_bar.hindrance(same) 

This is a spot difficult. Fundamentally, successful Ruby (and successful beautiful overmuch each azygous-dispatch based mostly OO languages), a technique is sure to a circumstantial receiver entity, known as same successful Ruby. Successful another phrases: a technique ever is aware of what entity it was referred to as connected, it is aware of what its same is. However, we grabbed the technique straight from a people, however does it cognize what its same is?

Fine, it doesn’t, which is wherefore we demand to hindrance our UnboundMethod to an entity archetypal, which volition instrument a Technique entity that we tin past call. (UnboundMethods can’t beryllium known as, due to the fact that they don’t cognize what to bash with out understanding their same.)

And what bash we hindrance it to? We merely hindrance it to ourselves, that manner it volition behave precisely similar the first barroom would person!

Lastly, we demand to call the Methodology that is returned from hindrance. Successful Ruby 1.9, location is any nifty fresh syntax for that (.()), however if you are connected 1.eight, you tin merely usage the call technique; that’s what .() will get translated to anyhow.

Present are a mates of another questions, wherever any of these ideas are defined:

“Soiled” Monkey Patching

alias_method concatenation

The job we are having with our monkey patching is that once we overwrite the methodology, the methodology is gone, truthful we can not call it anymore. Truthful, fto’s conscionable brand a backup transcript!

people Foo def barroom 'Hullo' extremity extremity people Foo alias_method :old_bar, :barroom def barroom old_bar + ' Planet' extremity extremity Foo.fresh.barroom # => 'Hullo Planet' Foo.fresh.old_bar # => 'Hullo' 

The job with this is that we person present polluted the namespace with a superfluous old_bar technique. This technique volition entertainment ahead successful our documentation, it volition entertainment ahead successful codification completion successful our IDEs, it volition entertainment ahead throughout observation. Besides, it inactive tin beryllium known as, however presumably we monkey patched it, due to the fact that we didn’t similar its behaviour successful the archetypal spot, truthful we mightiness not privation another group to call it.

Contempt the information that this has any undesirable properties, it has unluckily go popularized done AciveSupport’s Module#alias_method_chain.

An speech: Refinements

Successful lawsuit you lone demand the antithetic behaviour successful a fewer circumstantial locations and not passim the entire scheme, you tin usage Refinements to limit the monkey spot to a circumstantial range. I americium going to show it present utilizing the Module#prepend illustration from supra:

people Foo def barroom 'Hullo' extremity extremity module ExtendedFoo module FooExtensions def barroom ace + ' Planet' extremity extremity refine Foo bash prepend FooExtensions extremity extremity Foo.fresh.barroom # => 'Hullo' # We haven’t activated our Refinement but! utilizing ExtendedFoo # Activate our Refinement Foo.fresh.barroom # => 'Hullo Planet' # Location it is! 

You tin seat a much blase illustration of utilizing Refinements successful this motion: However to change monkey spot for circumstantial methodology?


Deserted concepts

Earlier the Ruby assemblage settled connected Module#prepend, location have been aggregate antithetic ideas floating about that you whitethorn often seat referenced successful older discussions. Each of these are subsumed by Module#prepend.

Technique Combinators

1 thought was the thought of methodology combinators from CLOS. This is fundamentally a precise light-weight interpretation of a subset of Facet-Oriented Programming.

Utilizing syntax similar

people Foo def barroom:earlier # volition ever tally earlier barroom, once barroom is referred to as extremity def barroom:last # volition ever tally last barroom, once barroom is referred to as # whitethorn oregon whitethorn not beryllium capable to entree and/oregon alteration barroom’s instrument worth extremity extremity 

you would beryllium capable to “hook into” the execution of the barroom methodology.

It is nevertheless not rather broad if and however you acquire entree to barroom’s instrument worth inside barroom:last. Possibly we might (ab)usage the ace key phrase?

people Foo def barroom 'Hullo' extremity extremity people Foo def barroom:last ace + ' Planet' extremity extremity 

Substitute

The earlier combinator is equal to prepending a mixin with an overriding technique that calls ace astatine the precise extremity of the technique. Likewise, the last combinator is equal to prepending a mixin with an overriding technique that calls ace astatine the precise opening of the technique.

You tin besides bash material earlier and last calling ace, you tin call ace aggregate instances, and some retrieve and manipulate ace’s instrument worth, making prepend much almighty than technique combinators.

people Foo def barroom:earlier # volition ever tally earlier barroom, once barroom is known as extremity extremity # is the aforesaid arsenic module BarBefore def barroom # volition ever tally earlier barroom, once barroom is known as ace extremity extremity people Foo prepend BarBefore extremity 

and

people Foo def barroom:last # volition ever tally last barroom, once barroom is referred to as # whitethorn oregon whitethorn not beryllium capable to entree and/oregon alteration barroom’s instrument worth extremity extremity # is the aforesaid arsenic people BarAfter def barroom original_return_value = ace # volition ever tally last barroom, once barroom is known as # has entree to and tin alteration barroom’s instrument worth extremity extremity people Foo prepend BarAfter extremity 

aged key phrase

This thought provides a fresh key phrase akin to ace, which permits you to call the overwritten methodology the aforesaid manner ace lets you call the overridden technique:

people Foo def barroom 'Hullo' extremity extremity people Foo def barroom aged + ' Planet' extremity extremity Foo.fresh.barroom # => 'Hullo Planet' 

The chief job with this is that it is backwards incompatible: if you person technique referred to as aged, you volition nary longer beryllium capable to call it!

Substitute

ace successful an overriding methodology successful a prepended mixin is basically the aforesaid arsenic aged successful this message.

redef key phrase

Akin to supra, however alternatively of including a fresh key phrase for calling the overwritten technique and leaving def unsocial, we adhd a fresh key phrase for redefining strategies. This is backwards suitable, since the syntax presently is amerciable anyhow:

people Foo def barroom 'Hullo' extremity extremity people Foo redef barroom aged + ' Planet' extremity extremity Foo.fresh.barroom # => 'Hullo Planet' 

Alternatively of including 2 fresh key phrases, we may besides redefine the that means of ace wrong redef:

people Foo def barroom 'Hullo' extremity extremity people Foo redef barroom ace + ' Planet' extremity extremity Foo.fresh.barroom # => 'Hullo Planet' 

Substitute

redefining a methodology is equal to overriding the methodology successful a prepended mixin. ace successful the overriding technique behaves similar ace oregon aged successful this message.