What is duck typing in Python, and how does it relate to polymorphism?
Duck typing means an object is accepted if it has the methods you call, regardless of its class. It gives polymorphism without a shared parent or interface.
Explain it simply
If it walks like a duck and quacks like a duck, treat it as a duck. A tea stall only cares whether you can pay; it does not ask whether you hold a UPI app, cash or a card.
In Python, a function that calls x.pay() works with any object that has a pay method. No common base class is required.
Example
class Upi:
def pay(self, amt): return f"UPI paid {amt}"
class Cash:
def pay(self, amt): return f"Cash paid {amt}"
def checkout(method, amt):
return method.pay(amt) # only needs a pay() method
print(checkout(Upi(), 120)) # UPI paid 120
print(checkout(Cash(), 80)) # Cash paid 80If an object lacks pay, you get an AttributeError at runtime. Type hints with Protocol can describe the shape for tools to check.
What to say in the interview
"Duck typing checks behaviour, not declared type: any object with the needed methods works. It gives polymorphism without inheritance, at the cost of errors appearing at runtime unless supported by tests or Protocol type hints."
Common mistakes
- Assuming Python polymorphism needs a common parent class.