What Is Duck Typing? Judging Objects by Behavior
Duck typing means an object suitability is judged by the methods and properties it actually has, not by its declared class: if it walks and quacks like a duck, treat it as one.
Common in dynamic languages like Python and Ruby, duck typing cares about behavior over identity. Code does not ask "is this object of type Duck?" It just calls the methods it needs and trusts the object to have them. This makes code flexible and loosely coupled, but it moves the safety net entirely to runtime and to your tests.
The idea behind duck typing
Instead of checking an object declared type, duck typing checks whether it supports the operations you need. Any object with the right methods works, regardless of its class or inheritance. The interface is implicit: it is whatever the code happens to use.
Why duck typing is handy
- Loose coupling: code depends on behavior, not concrete types.
- Easy substitution, including with test doubles and mocks.
- Less boilerplate than declaring formal interfaces.
- Natural polymorphism without an inheritance hierarchy.
The risks
Because nothing checks the contract ahead of time, passing an object that is missing a method fails only at runtime, when that method is called. The implicit interface is also undocumented, so it is easy to break without noticing.
Duck typing and tests
With no compiler verifying that objects fit, tests carry the burden of confirming the right methods exist and behave correctly. Thorough tests are how duck-typed code stays reliable, since errors otherwise surface only in production.
A quick example
A function that calls obj.read() works with a file, a network stream, or a fake in-memory object, anything with a read method, without caring about their types.
Duck typing in CI
A missing-method error from a duck-typing mismatch is a deterministic bug that fails identically every run, so retrying does not help. Latchkey auto-retries only transient infrastructure failures, leaving genuine duck-typing errors visible so they get fixed.
Key takeaways
- Duck typing judges objects by the methods they have, not their declared type.
- It is flexible and loosely coupled but defers all checking to runtime and tests.
- Missing-method errors are deterministic bugs, not transient failures to retry.