220. Duck Typing vs. Structural Typing

πŸ”Ή 1. Classic Duck Typing Example

Copy

class Dog:
    def speak(self):
        return "Woof!"

class Cat:
    def speak(self):
        return "Meow!"

def animal_sound(animal):
    return animal.speak()  # No type checking, relies on method existence

print(animal_sound(Dog()))  # βœ… Output: Woof!
print(animal_sound(Cat()))  # βœ… Output: Meow!

βœ… Fix: Python doesn’t check Dog or Cat type, only if speak() exists.


πŸ”Ή 2. Duck Typing Fails Without Required Methods

Copy

class Fish:
    def swim(self):
        return "I swim"

print(animal_sound(Fish()))  # ❌ AttributeError: 'Fish' object has no attribute 'speak'

❌ Issue: Fish has swim(), but no speak(), so it crashes. βœ… Fix: Use hasattr(animal, "speak") before calling.


πŸ”Ή 3. Structural Typing with Protocol (Python 3.8+)

Copy

βœ… Fix: Protocol enforces speak() presence at runtime.


πŸ”Ή 4. Runtime Check for Structural Typing

Copy

βœ… Fix: Check compliance before calling speak().


πŸ”Ή 5. Multiple Method Requirements in Protocol

Copy

βœ… Fix: Enforces multiple method contracts.


πŸ”Ή 6. Duck Typing with try-except to Handle Missing Methods

Copy

βœ… Fix: Catch missing attributes dynamically.


πŸ”Ή 7. Structural Typing for Function Arguments

Copy

βœ… Fix: Ensures draw() method exists before calling.


πŸ”Ή 8. Combining Duck Typing & Type Hints

Copy

βœ… Fix: Duck typing with hasattr().


πŸ”Ή 9. Structural Typing with @staticmethod

Copy

βœ… Fix: @staticmethod inside Protocol.


πŸ”Ή 10. Mixing Duck Typing & Structural Typing

Copy

βœ… Fix: Duck typing (hasattr()) vs. Structural typing (Protocol).


πŸš€ Summary: Duck Typing vs. Structural Typing

Feature

Duck Typing

Structural Typing (Protocol)

Definition

Checks if an object has required methods at runtime.

Defines expected method names at type-check time.

Flexibility

High (any object can pass if it has required methods).

Stricter (only objects implementing the interface are allowed).

Error Handling

Prone to AttributeError.

Detects issues before execution.

Type Checking

Implicit (hasattr(), try-except).

Explicit (Protocol enforces structure).

Performance

Slightly faster (no static checks).

Slightly slower (type checking at runtime).


πŸ’‘ When to Use?

Scenario

Use

General Python coding

βœ… Duck Typing (simpler, flexible).

Large-scale projects

βœ… Structural Typing (prevents runtime errors).

Library/Public API design

βœ… Structural Typing (Protocol ensures correctness).

One-off scripts

βœ… Duck Typing (less code, more flexibility).


Last updated