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