• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

Monkey Patching in Python Explained with Coding Examples

Aniruddha Chaudhari/18438/0
CodePython

Explaining monkey patching in Python with simple examples so that everyone can understand. In this tutorial, I will mention its use-case where you can use it in your project or program.

What is Monkey Patching?

This question also has been asked in the many Python job interviews.

Monkey patching is a dynamic technique in Python by which you can modify the behavior of an existing class or module.

To change the behavior of a class or module, you don’t need to change the code inside the class or method.

Let’s see how you can do that.

I’m taking two coding examples to change the behavior of the class and module.

Example: Monkey Patching Python Class

Python program to change the behavior of class dynamically:

class monkey:
    def monkeyFunc(self):
        print("my function")
        
def patchFunc():
    print("patching on monkey")
    

#normal class method call
objMonkey= monkey()
objMonkey.monkeyFunc()

#calling class method after monkey patch
objMonkey.monkeyFunc=patchFunc
objMonkey.monkeyFunc()

Output:

my function
patching on monkey

In the above program, we have created an instance objMonkey of class monkey.

We are assigning a new method name (patchFunc) to the existing class method name (monkeyFunc). The linking of a new method to the existing class method name happens at runtime. So the behavior of the class monkey is changed dynamically.

In the above class, you are changing the behavior of the class method defined in the same program file.

Now let’s take another example of a monkey patching Python module.

Example: Monkey Patching Python Module

Write your own modules called animals.

class monkey:
    def monkeyFunc(self):
        print("my function")

Save this file as animals.py.
Now import this file as a Python module in your another Python program.

import animals

def patchFunc():
    print("patching on monkey")

#normal class method call
objMonkey= animals.monkey()
objMonkey.monkeyFunc()
 
#calling class method after monkey patch
objMonkey.monkeyFunc=patchFunc
objMonkey.monkeyFunc()

Output:

my function
patching on monkey

We are getting the same output. This time we have changed the behavior of the method defined inside the module animals without changing a single line of code inside the animals.py.

In this example, I tried the monkey patching my own module. Similarly, you can try it on existing standard modules.

[Use-Case] What’s the use of monkey patching?

Let’s take an example.

Suppose you are importing the standard module. Modules have different methods.

As per your requirement, you want the method inside the module to work differently. It’s not easy to go to the method defined inside the standard module and change it.

The simplest way of doing the same things is by the monkey patching technique.

How does it work?

  • You write your own method.
  • Assign this method name to the method name defined inside the module.
  • Now every time when you call the method defined inside the module, it calls your own method.

You changed the behavior of the method defined in the module.

Conclusion

This is all about monkey patching in Python- a technique to change the behavior of a class or module.

There is also another technique called decorators in Python to change the behavior of code without changing the actual code dynamically.

Python Interview Questions eBook

Python
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard