
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Explain monkey patching in Python?
Monkey patching is the technique of dynamic modification of a piece of code at the run time. Actually by doing monkey patch we change the behavior of code but without affecting the original source code.
History
The monkey patch comes from the word guerrilla patch, guerrilla nearly means gorilla which can define the monkey species. The guerrilla patch refers to change sneakily. But money patch seems easy to pronounce, so now it's known as “ Monkey patch“. In the word “Monkey-patch” the word monkey defines the word dynamic.
Monkey patching in python
Monkey patching in python refers to modifying or updating a piece of code or class or any module at the runtime. In simple words, we can change the behavior or working of a class/ module at the runtime without changing the whole python code. But sometimes monkey patching is considered bad practice because the definition of object does not accurately describe how the object is behaving in the code.
Example
class first: def print(self) print(“hello world”)
Output
If we run the above code it will generate the following output −
Hello world
Code after monkey patching
Example
Import monkey def monkey_function(self): print(“Hello world”) # updating the print() with monkey_function() monkey.A.print = monkey_function # revoking method print() as method monkey_function() obj = monkey.A() obj print()
Output
If we run the above code it will generate the following output −
Hello world
- Related Articles
- Patching Array in C++
- The Monkey and the Crocodile
- What is Monkey & Gorilla Testing? Examples, Difference
- What to do if you are bitten by a monkey?
- Explain calendar module in python?
- Explain Binary Search in Python
- Explain Merge Sort in Python
- Explain function of % operator in Python.
- Explain Stack in Python with examples
- Explain Python vs Scala
- Explain str() vs repr() functions in Python
- Explain try, except and finally statements in Python.
- Explain Try, Except and Else statement in Python.
- Explain briefly the Object oriented concepts in Python?
- Explain subn() methods of “re” module in Python ?
