Duck Typing
Overview
Python relies heavily on a philosophy called 'Duck Typing' (If it walks like a duck and quacks like a duck, it must be a duck). Unlike strongly-typed languages like Java that require strict Interface implementations, Python does not care what specific Class an object belongs to. It only cares whether the object possesses the required methods or attributes at the exact moment they are called. This promotes maximum flexibility and underpins the 'Easier to Ask for Forgiveness than Permission' (EAFP) coding style.
Syntax
class Duck:
def make_sound(self): print("Quack!")
class Robot:
def make_sound(self): print("Beep Boop!")
# This function has no idea what 'entity' is.
# It doesn't check types. It just assumes the method exists.
def trigger_sound(entity):
entity.make_sound()
trigger_sound(Duck()) # Quack!
trigger_sound(Robot()) # Beep Boop!Common Pitfalls
- Over-using
isinstance()to aggressively check types before executing logic (Look Before You Leap). This explicitly violates Duck Typing and makes your code rigid. Instead, just call the method and use atry/exceptblock to catch theAttributeErrorif the object doesn't support it.
Interview Questions
Easier to Ask for Forgiveness than Permission. It is the core Python philosophy of assuming an object has the required structure and catching exceptions if it fails, rather than writing heavy if statements to validate the object beforehand.
Real-World Example
Writing to multiple disparate outputs seamlessly.
def log_data(output_stream, message):
# output_stream could be a File object, sys.stdout,
# or a custom Network Socket. We don't check the type.
# As long as it has a .write() method, it works perfectly.
output_stream.write(message + "\n")Check Your Knowledge
Test your understanding of Duck Typing with these quick questions.