220. Duck Typing vs. Structural Typing
🔹 1. Classic Duck Typing Example
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
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+)
✅ Fix: Protocol enforces speak() presence at runtime.
🔹 4. Runtime Check for Structural Typing
✅ Fix: Check compliance before calling speak().
🔹 5. Multiple Method Requirements in Protocol
✅ Fix: Enforces multiple method contracts.
🔹 6. Duck Typing with try-except to Handle Missing Methods
✅ Fix: Catch missing attributes dynamically.
🔹 7. Structural Typing for Function Arguments
✅ Fix: Ensures draw() method exists before calling.
🔹 8. Combining Duck Typing & Type Hints
✅ Fix: Duck typing with hasattr().
🔹 9. Structural Typing with @staticmethod
✅ Fix: @staticmethod inside Protocol.
🔹 10. Mixing Duck Typing & Structural Typing
✅ 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