Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I am trying to understand, what is monkey patching or a monkey patch?

Is that something like methods/operators overloading or delegating?

Does it have anything in common with these things?

1 Answer

0 votes
by (106k points)

Actually, it's not like any of those things. It is simply the dynamic replacement of attributes at runtime.

MonkeyPatch:-

It is a piece of Python code which extends or modifies other code at runtime.

We will understand MonkeyPatch by an example so, for instance, let us consider a class that has a method get_data. This method get_data does an external lookup (on a database or web API, for example), and various other methods in the class call it. When dealing with a unit test, you don't want to depend on the external data source - so you dynamically replace the get_data method with a stub that returns some fixed data.

Why we use it because Python classes are mutable, and methods are just attributes of the class, you can do this as much as you like - and, in fact, you can even replace classes and functions in a module in exactly the same way.

You should use some caution when dealing with  monkey patching:

  • If anything else besides your test logic calls get_data as well, it will also call your monkey-patched replacement rather than the original -- which can be good or bad. Just beware.

  • Let, if there is some variable or attribute exists that also points to the get_data function by the time you replace it, this alias will not change its meaning and will continue to point to the original get_data. 

Related questions

0 votes
1 answer
asked Apr 11, 2021 in Linux by dev_sk2311 (45k points)

Browse Categories

...