Monkey Patching in Python

Monkey Patching in Python

Monkey Patching is an exciting topic of Python. Monkey-patching is a term that refers to modifying a class or module at a run time. In simple words, a class or module’s work can be changed at the runtime. Let’s understand this concept by real-life example.

When we work on a large project, we may encounter a situation where the third-party library is not working well. So we attempt to revise (or change) it from our project. This process is known as monkey patching in Python. Generally, it is avoided by the developer. However, it is a part of the development process.

In monkey patching, we can reopen the class and modify its behavior

We will learn how we can use monkey-patching in using the Python code.

We know that Python is a dynamic language; classes are mutable, so we can alter them when we want. Let’s understand the following example.

Example –

Output:

30
[('__init__', >), ('add', >)]

As we can see in the above code, there are two methods in the above class – __init__ and addition. We called the add() method and passed 20 as an argument. It retuned 30. We have defined the MultiPatch class with the add() method. Suppose we add the new method to the MonkeyPatch class.

To add the divide() method to MonkeyPatch class, simply assign the divide function to MonkeyPatch.

The newly created function would be available in the MonkeyPatch class. Let’s see the following example.

Output:

[('__init__', >), ('subtraction', >)]

Dynamic Behavior of Function

Let’s see another example to understand the dynamic behavior in better way.

Example –

We have created a module which will use in the below code to change the behavior of hello() function at runtime.

Output:

monkey_f() is being called

Memory Address Changing

Python provides the ctype module, which is used to change the value of an object by memory address management. So it is not recommended to do, direct memory manipulation is unsafe and not consistent. Possibly, it can work with one value and not for another.

Conclusion

We have discussed how we can achieve the monkey-patching in Python. But it consists of few disadvantages and should be used carefully. It is not good to use in application design because it distinguishes the source code on disk and the observed behavior. Developer can be confused while debugging.


原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263528.html

(0)
上一篇 2022年5月30日
下一篇 2022年5月30日

相关推荐

发表回复

登录后才能评论