Friday, March 25, 2022

Duck typing

Duck typing, sometimes referred to as dynamic typing, is mostly adopted in programming languages that support dynamic typing, such as Python and JavaScript. The name duck typing is borrowed based on the following quote:

"If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck." This means that if a bird is behaving like a duck, it will likely be a duck. The point of mentioning this quote is that it is possible to identify an object by its behavior, which is the core principle of duck typing in Python.

In duck typing, the type of class of an object is less important than the method (behavior) it defines. Using duck typing, the types of the object are not checked, but the method that is expected is executed.
To illustrate this concept, we take a simple example with three classes, Car, Cycle, and Horse, and we try to implement a start method in each of them. In the Horse class, instead of naming the method start, we call it push. Here is a code snippet with all three classes and the main program at the end:

#ducttype1.py
class Car:
def start(self):
print ("start engine by ignition /battery")
class Cycle:
def start(self):
print ("start by pushing paddles")

class Horse:
def push(self):
print ("start by pulling/releasing the reins")
if __name__ == "__main__":
for obj in Car(), Cycle(), Horse():
obj.start()

In the main program, we try to iterate the instances of these classes dynamically and call the start method. As expected, the obj.start() line failed for the Horse object because the class does not have any such method. As we can see in this example, we can put different class or instance types in one statement and execute the methods across them.

If we change the method named push to start inside the Horse class, the main program will execute without any error. Duck typing has many use cases, where it simplifies the solutions. Use of the len method in many objects and the use of iterators are a couple of many examples.


Share:

0 comments:

Post a Comment