Duck typing lets you use any object that behaves the way you expect, without worrying about its exact type.
Duck typing concept in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
def function(obj): obj.some_method() # No need to check obj's type, just use its methods
Python does not require you to declare types explicitly.
If the object has the method or attribute used, it works; otherwise, it raises an error.
Examples
quack method, so make_it_quack works with either.Python
class Duck: def quack(self): print("Quack!") class Person: def quack(self): print("I'm pretending to be a duck!") def make_it_quack(thing): thing.quack() make_it_quack(Duck()) make_it_quack(Person())
quack, so calling make_it_quack raises an error.Python
class Dog: def bark(self): print("Woof!") def make_it_quack(thing): thing.quack() make_it_quack(Dog()) # This will cause an error
Sample Program
This program shows duck typing by calling fly() on different objects that both have this method.
Python
class Bird: def fly(self): print("Flying high!") class Airplane: def fly(self): print("Zooming through the sky!") def let_it_fly(flyer): flyer.fly() bird = Bird() airplane = Airplane() let_it_fly(bird) let_it_fly(airplane)
Important Notes
Duck typing focuses on what an object can do, not what it is.
Be careful: if an object lacks the expected method, your program will raise an error.
You can use hasattr() to check if an object has a method before calling it.
Summary
Duck typing means using objects based on their behavior, not their type.
It makes code flexible and easy to reuse with different objects.
Errors happen only if the object does not have the needed methods or properties.
Practice
1. What does
duck typing in Python primarily focus on?easy
Solution
Step 1: Understand the meaning of duck typing
Duck typing means if an object behaves like a duck (has methods/attributes), it can be used as a duck, regardless of its actual type.Step 2: Compare options with this meaning
Only Using an object based on its methods and behavior, not its type matches this idea by focusing on behavior, not type checking.Final Answer:
Using an object based on its methods and behavior, not its type -> Option CQuick Check:
Duck typing = behavior over type [OK]
Hint: Focus on behavior, not type, to identify duck typing [OK]
Common Mistakes:
- Thinking duck typing requires strict type checks
- Confusing duck typing with inheritance
- Believing duck typing only works with built-in types
2. Which of the following Python code snippets correctly demonstrates duck typing?
easy
Solution
Step 1: Identify duck typing usage
Duck typing means using an object if it has the needed method, without checking its type.Step 2: Analyze each option
def quack(duck): if hasattr(duck, 'quack'): duck.quack() class Duck: def quack(self): print('Quack!') quack(Duck()) useshasattrto check for method presence, which fits duck typing. Options B and C check type explicitly, which is not duck typing. def quack(duck): duck.quack() class Duck: def quack(self): print('Quack!') quack(Duck()) assumes the object has the method but does not check, which is okay but less safe than A.Final Answer:
Using hasattr to check method presence before calling -> Option AQuick Check:
hasattr check = duck typing safe use [OK]
Hint: Look for method presence checks, not type checks [OK]
Common Mistakes:
- Confusing type checking with duck typing
- Ignoring method presence before calling
- Assuming duck typing requires no checks at all
3. What will be the output of the following code?
class Bird:
def fly(self):
print('Flying')
class Airplane:
def fly(self):
print('Jet flying')
objects = [Bird(), Airplane()]
for obj in objects:
obj.fly()medium
Solution
Step 1: Understand the objects and their fly methods
Bird has fly() printing 'Flying', Airplane has fly() printing 'Jet flying'.Step 2: Trace the loop calling fly on each object
First object is Bird(), prints 'Flying'. Second is Airplane(), prints 'Jet flying'.Final Answer:
Flying\nJet flying -> Option AQuick Check:
Each object's fly() runs in order [OK]
Hint: Each object's method runs in loop order [OK]
Common Mistakes:
- Assuming type matters for method call
- Mixing output order
- Expecting error due to different classes
4. Identify the error in this code using duck typing and fix it:
class Cat:
def meow(self):
print('Meow')
def make_sound(animal):
animal.sound()
make_sound(Cat())medium
Solution
Step 1: Identify the method called on the object
Function callsanimal.sound(), but Cat class hasmeow(), notsound().Step 2: Fix the method call to match Cat's method
Changeanimal.sound()toanimal.meow()to call the existing method.Final Answer:
Change animal.sound() to animal.meow() -> Option DQuick Check:
Method name must match object's method [OK]
Hint: Match method names exactly when using duck typing [OK]
Common Mistakes:
- Calling a method that does not exist
- Adding unnecessary type checks
- Ignoring method name mismatch
5. You want to write a function
process(item) that works with any object having a serialize() method. Which approach best uses duck typing to handle objects without serialize() safely?hard
Solution
Step 1: Understand duck typing safety
Duck typing uses behavior, so checking method presence withhasattris a safe way to confirm before calling.Step 2: Compare options for best practice
Useif hasattr(item, 'serialize'):before callingitem.serialize()checks method presence explicitly, fitting duck typing. Wrapitem.serialize()call in try-except to catch AttributeError uses try-except but is less clear and may hide other errors. Check iftype(item) == Serializerbefore callingserialize()checks type, which is not duck typing. Define a base class with serialize() and inherit all objects from it requires inheritance, reducing flexibility.Final Answer:
Use if hasattr(item, 'serialize') before calling item.serialize() -> Option BQuick Check:
hasattr check = safe duck typing [OK]
Hint: Check method presence with hasattr before calling [OK]
Common Mistakes:
- Using type checks instead of behavior checks
- Ignoring method presence and causing errors
- Overusing try-except hiding bugs
