Duck Typing
"If it walks like a duck and quacks like a duck, it is a duck."
What is Duck Typing?
In Python, what matters is not what an object is, but what it can do. Python does not check an object's class before calling a method. It simply tries to call the method. If the object has it, great. If not, you get an error.
This means two completely unrelated classes can be used interchangeably -- as long as they have the same methods. No shared parent class required.
Dog and Robot -- No Relation, Same Method
class Dog:
def speak(self):
return "Woof!"
class Robot:
def speak(self):
return "Beep boop!"
def make_it_speak(thing):
print(thing.speak())
make_it_speak(Dog()) # Woof!
make_it_speak(Robot()) # Beep boop!
Key point: Dog and Robot have no parent class in common. They are completely unrelated. But because both have a speak() method, the function make_it_speak() works with both. That is duck typing.
Duck Typing vs Strict Typing
| Python (Duck Typing) | Java / C++ (Strict Typing) |
|---|---|
| Checks if the method exists at runtime | Checks the class type at compile time |
| No shared parent needed | Must share a parent class or interface |
| More flexible, less formal | Safer at compile time, more rigid |
Practical Example: Anything with read()
In real applications, you often need to read data from different sources. With duck typing, any object that has a read() method can be used -- files, APIs, databases, or even mock objects for testing.
class FileReader:
def read(self):
return "data from file"
class APIReader:
def read(self):
return "data from API"
class MockReader:
def read(self):
return "fake test data"
def process(reader):
data = reader.read()
print(f"Processing: {data}")
# All three work -- no shared parent class
process(FileReader()) # Processing: data from file
process(APIReader()) # Processing: data from API
process(MockReader()) # Processing: fake test data
Why this matters: You can swap data sources without changing the process() function at all. This makes your code flexible and easy to test.
Best Practices
- Write functions that depend on methods, not on class types. Avoid
isinstance()checks when possible. - Use clear, descriptive method names so other developers know what interface to implement.
- Use try/except to handle cases where an object might not have the expected method, providing a helpful error message.
Common Mistakes
- Passing an object that is missing the required method -- you will get an
AttributeErrorat runtime, not at write time. - Having methods with the same name but different signatures (different parameters) across classes -- this breaks the implicit contract.
- Over-relying on duck typing without any documentation -- other developers need to know which methods are expected.
Practice Exercises
Exercise 1: Loggers
Create three unrelated classes: ConsoleLogger, FileLogger, and CloudLogger. Each should have a log(message) method. Write a function that accepts any logger and uses it.
Exercise 2: Drawable Things
Create classes Circle, Button, and TextBox -- each with a draw() method. Write a render_all(items) function that loops through and draws each one.
Exercise 3: Error Handling
Write a function safe_speak(thing) that uses try/except to call thing.speak() and prints a friendly error if the method does not exist.
Summary
- Duck typing: Python cares about what methods an object has, not what class it belongs to.
- Unrelated classes can be used interchangeably if they share the same method names.
- This makes Python extremely flexible but requires discipline with method naming.
- Errors from missing methods only appear at runtime, so test your code carefully.