Duck Typing
Subject: Computer and Technology noun /ˈdʌk ˌtaɪ.pɪŋ/ 1 definition
- programming-languages
- type-systems
- object-oriented-programming
- dynamic-typing
-
Definition (noun)
Entry #259 · UpdatedDuck Typing is a type-checking discipline in which an object's suitability for an operation is determined by the methods and properties it exposes rather than its explicit class or inheritance hierarchy. Named after the duck test ("if it walks like a duck and quacks like a duck, then it must be a duck"), it enables polymorphism across unrelated types without requiring shared base classes or formal interface declarations. Unlike nominal typing, which enforces compatibility through declared type names ahead of execution, classic duck typing validates behavior at the point of use, increasing flexibility while shifting interface mismatches to runtime.
Common Forms
Runtime Duck Typing: Common in dynamically typed languages such as Python, Ruby, and JavaScript, where method and attribute lookups occur during execution and missing members raise runtime exceptions.
Static Duck Typing: Supported by systems such as Python's
typing.Protocoland Go's implicit interfaces, allowing static checkers or compilers to verify required method signatures structurally without explicit subclassing.Template-Based Duck Typing: Used in generic mechanisms like C++ templates, where the compiler validates that a substituted type supports all invoked operations during template instantiation rather than against a named base interface.
Feature-Detection Duck Typing: A defensive runtime pattern that probes whether expected properties or callable methods exist (such as via
hasattrin Python ortypeofchecks in JavaScript) before invoking them, avoiding rigid class checks.
Example
A Python reporting utility calls
destination.write(summary)without checking whetherdestinationinherits fromio.IOBase. Thanks to duck typing, the function works identically with an open disk file, anio.StringIObuffer, or an unrelated customSlackWebhookWriterclass as long as each exposes a compatible.write()method.