- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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