Glossary

Duck Typing

Duck typing is a programming philosophy summed up by the phrase "if it walks like a duck and quacks like a duck, it's a duck." In Python, this means that the type of an object is less important than the methods and attributes it provides. A function that calls obj.read() works with files, StringIO objects, HTTP responses, or any custom class that has a read() method — without checking the type.

Duck typing is fundamental to Python's design. The for loop works with any object that implements __iter__ (or __getitem__ as a fallback). The len() function works with any object that implements __len__. The + operator works with any object that implements __add__. Python rarely checks types explicitly; it just tries to use the object and raises an exception if the required method is missing.

Duck typing enables remarkable flexibility: you can substitute mock objects in tests, create proxy objects that delegate to wrapped objects, and write generic functions that work across many types. The downside is that errors are detected at runtime rather than at compile time. Protocols (from the typing module) bring duck typing into the type-checking world by letting you declare structural interfaces that static analysers can verify — duck typing with a safety net.

Related terms: Protocol, Dunder Method, Dynamic Typing

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.