Duck Typing & Monkey Patching

Introduction:

There is common saying that if I see a bird-

If it quack like a duck and swims like duck then it has to be duck.

Duck typing in Python gives a programmer the ability to not worry about the type of a class rather perform the required operation.

When your create an object, can your object perform certain task. If yes, then its great to have the Object. No matter if the object is of Class A or Class B.

Code:

Let’s understand Duck typing through a simple Code Snippet in Python:

Step1: Created a Class Duck and defined 2 methods(function)- quack and fly.
Step2: Created another Class Chicken and defined the same 2 methods as previous class.
Step3: Now created the 3rd Class Bird which task is to invoke the 2 methods-quack and fly from behavior method
Step4: Create an instance of each Classes- Bird, Chicken and Duck
Step5: Comment the Chicken instance and pass duck1 as argument to bird1.behavior(duck1). You see output as –

Step6: Now comment the Duck instance and uncomment duck1 = Chicken() and pass duck1 as argument to bird1.behavior(duck1). You see output as –

So no matter which class your object is created for. If it can perform(execute) the quack and fly method, it is considered to be the Duck.

Monkey Patching:

In Python, the term monkey patch refers to dynamic (or run-time) modifications of a class or module. In Python, we can actually change the behavior of code at run-time.

Code:

Let’s understand Monkey Patching through a simple Code Snippet in Python:

Step1: As said, we can actually change the behavior of code at run-time.
Step2: Create a Class called Employee and method emp_func()
Step3: Defined an outer function monkey_function()
Step4: Now we call the emp_func() from the Employee object, it will print- “This Employee function“.
Step5: But if we pass the monkey_function as Employee.emp_func  directly, it will change the functionality of emp_func at runtime and will print- “This is Monkey Fucntion”

Conclusion:

Duck-Typing is more pythonic way of defining class and objects. You can find more reference from the below-

Duck-Typing:

https://youtu.be/CuK0g8OFzwo

https://youtu.be/x3v9zMX1s4s

Monkey Patch:

https://www.geeksforgeeks.org/monkey-patching-in-python-dynamic-behavior/ https://youtu.be/wKpEq5_yW9E