Duck Typing in Python 🦆🐍

Duck Typing is a concept in dynamic typing where the type of an object is determined by its behavior rather than its inheritance or explicit type declaration.
🔹 Famous Quote:
"If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck."
In Python, an object's compatibility with an operation is based on what methods or attributes it has, rather than its actual class.
1️⃣ Understanding Duck Typing
📌 In statically typed languages (like Java, C++), the type of a variable is explicitly declared.
📌 In dynamically typed languages (like Python), we don’t need to declare types—Python determines them at runtime.
🚫 Without Duck Typing (Static Typing in Java)
class Dog {
void speak() {
System.out.println("Bark");
}
}
class Cat {
void speak() {
System.out.println("Meow");
}
}
public class Main {
public static void makeSound(Dog d) { // Only accepts Dog
d.speak();
}
public static void main(String[] args) {
Dog dog = new Dog();
Cat cat = new Cat();
makeSound(dog); // ✅ Works
makeSound(cat); // ❌ Error (Incompatible type)
}
}
🔹 Java requires explicit types—makeSound(Dog d) only works for Dog, not Cat.
✅ With Duck Typing (Python’s Dynamic Typing)
class Dog:
def speak(self):
return "Bark"
class Cat:
def speak(self):
return "Meow"
class Human:
def speak(self):
return "Hello!"
def make_sound(entity): # No type checking, just expects a `speak()` method
return entity.speak()
dog = Dog()
cat = Cat()
human = Human()
print(make_sound(dog)) # ✅ Bark
print(make_sound(cat)) # ✅ Meow
print(make_sound(human)) # ✅ Hello!
🔹 Python doesn’t care what type the object is—as long as it has a speak() method, it works.
2️⃣ Practical Example: Duck Typing in Action
✅ File Handling (Duck Typing with write())
class FileWriter:
def write(self, text):
print(f"Writing to a file: {text}")
class Logger:
def write(self, text):
print(f"Logging message: {text}")
def save_data(destination, text):
destination.write(text) # Expects a 'write()' method
file = FileWriter()
log = Logger()
save_data(file, "Hello, File!") # ✅ Works
save_data(log, "Hello, Log!") # ✅ Works
🔹 Both FileWriter and Logger implement write(), so they are interchangeable in save_data().
3️⃣ Duck Typing vs. Type Checking (isinstance())
📌 Avoid explicit type checks (isinstance())—it goes against Duck Typing principles.
🚫 Bad Practice (Explicit Type Checking)
def make_sound(entity):
if isinstance(entity, Dog):
return entity.speak()
elif isinstance(entity, Cat):
return entity.speak()
else:
raise TypeError("Unsupported type")
✅ Better Practice (Duck Typing)
def make_sound(entity):
return entity.speak() # Only expects a speak() method
🔹 Advantage: More flexible and extensible—new classes don’t need explicit changes to make_sound().
4️⃣ When to Use Duck Typing?
✅ When writing generic functions or methods that work with multiple object types.
✅ When interface compliance is more important than inheritance.
✅ When implementing polymorphism without strict type checks.
5️⃣ Summary
Concept Description Example
Duck Typing Determines type based on behavior (methods) make_sound(obj) works for any class with speak()
No Type Checking Python doesn’t require explicit type enforcement No need for isinstance()
More Flexible Works with any object that implements required methods write() method can be used for FileWriter, Logger, etc.
Date: 2025-03-24 00:00:00.000000