In Python, what is 'Duck Typing'?

Understanding Duck Typing in Python

Duck typing is a programming style embraced in Python which doesn't require us to know the type of an object before invoking an existing method on it.

The term "duck typing" itself originates from a metaphorical phrase that goes, "If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck." Meaning, an object's suitability for a task is determined by its methods and properties, not by its class or type.

For instance, let's think of a function, which expects its argument object to have a certain method. The function can still use objects of any type, as long as they have the required method. The function doesn't need to know the exact class or type of those objects. Here's a simple illustrative Python code:

def quack(duck):
    duck.quack()

class Duck:
    def quack(self):
        print("Quack!")

class NotADuck:
    def quack(self):
        print("I'm not a duck, but I can quack!")

duck = Duck()
not_a_duck = NotADuck()

quack(duck)        # Output: Quack!
quack(not_a_duck)  # Output: I'm not a duck, but I can quack!

In this example, as long as the object has a quack method, we can use it as an argument in our function, regardless of the object's class or type.

This style of programming promotes code reusability and can make your code more flexible. However, it's important to remember that it can also cause problems if care is not exercised. Errors can occur at runtime if objects do not have the expected attributes or methods.

Practicing defensive programming, like checking the presence of a method before calling it, can mitigate these potential problems. Python provides built-in functions such as hasattr() to check if an object possesses a certain attribute or method. Use these to ensure that your 'ducks' can really 'quack'.

Do you find this helpful?