Skip to main content
Definition Website Computer and Technology

Duck Typing

Subject: Computer and Technology noun /ˈdʌk ˌtaɪ.pɪŋ/ 1 definition

  1. Definition (noun)

    Entry #259 · Updated

    Duck 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.Protocol and 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 hasattr in Python or typeof checks in JavaScript) before invoking them, avoiding rigid class checks.

    Example

    A Python reporting utility calls destination.write(summary) without checking whether destination inherits from io.IOBase. Thanks to duck typing, the function works identically with an open disk file, an io.StringIO buffer, or an unrelated custom SlackWebhookWriter class as long as each exposes a compatible .write() method.