Duck typing is a programming idea where an object’s type matters less than what the object can do.
The name comes from the phrase:
If it walks like a duck and quacks like a duck, then it is a duck.
Why it is useful
Duck typing makes code more flexible. Instead of forcing every object to inherit from the same parent class or implement a formal interface, the code can work with any object that supports the needed behavior.
Tradeoff
Duck typing can make programs easier to extend, but errors may show up at runtime instead of earlier.
For example:
class Rock:
pass
make_it_speak(Rock())This fails because Rock does not have a speak() method.
Duck Typing vs Static Typing
With static typing, a function usually declares what type of object it accepts.
With duck typing, the function is more interested in behavior:
def save(file_like_object):
file_like_object.write("data")Any object with a write() method can be used here. It could be a real file, an in-memory buffer, or a custom object.
Key idea
Duck typing focuses on what an object can do, not what an object officially is.