Polymorphism & Abstraction
Duck Typing
Python philosophy of behavior-based typing
Interview: Python philosophy — tests understanding of dynamic typing, EAFP vs LBYL, and protocol-based design
Duck typing is a core Python philosophy: "If it walks like a duck and quacks like a duck, it's a duck." Python doesn't check an object's type — it checks whether the object has the required methods/attributes. This enables flexible, decoupled code that works with any compatible object.
EAFP vs LBYL
- EAFP: "Easier to Ask Forgiveness than Permission" — try it, catch errors (Pythonic)
- LBYL: "Look Before You Leap" — check types/attributes before using (less Pythonic)
- Duck typing naturally follows EAFP: just call the method, handle AttributeError if it fails
Protocols and Duck Typing
Python's built-in protocols (iteration, context managers, comparison) are all duck-typed. Any object that implements __iter__ is iterable, regardless of its type. This is the foundation of Python's flexibility.
Interview Tip
Be ready to discuss the trade-offs: duck typing is flexible but can fail at runtime. Static typing with Protocols gives you safety while maintaining duck typing's flexibility.
Use Cases
Writing functions that work with any compatible object (not just specific types)
Plugin systems: any class with required methods can be a plugin
Testing: mock objects that mimic real object interfaces
File-like objects: anything with read()/write() works as a stream
Iterables: anything with __iter__ works in for loops and comprehensions
Common Mistakes
Using isinstance() checks instead of duck typing (too restrictive)
Not handling AttributeError when duck-typed methods are missing
Assuming duck typing means no validation — still validate critical inputs
Over-using LBYL (hasattr checks) instead of EAFP (try/except)
Not documenting what methods/attributes your function expects