Bird
Raised Fist0
Pythonprogramming~10 mins

Duck typing concept in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Duck typing concept
Object passed to function
Check if object has needed method
Call method
Use result
Duck typing means using an object if it has the needed method or behavior, without checking its exact type.
Execution Sample
Python
class Duck:
    def quack(self):
        return "Quack!"

def make_it_quack(thing):
    return thing.quack()
This code calls quack() on any object passed in, trusting it has that method.
Execution Table
StepActionObject TypeMethod CalledResult
1Pass Duck instance to make_it_quackDuckNoneNone
2Check if object has quack methodDuckquackYes
3Call quack methodDuckquack"Quack!"
4Return resultDuckquack"Quack!"
5Pass string to make_it_quackstrNoneNone
6Check if object has quack methodstrquackNo
7Raise AttributeErrorstrquackError: 'str' object has no attribute 'quack'
💡 Execution stops when method is called or error is raised if method missing.
Variable Tracker
VariableStartAfter Step 1After Step 5Final
thingNoneDuck instancestring 'hello'Depends on call
Key Moments - 2 Insights
Why does make_it_quack work with any object that has quack(), not just Duck?
Because the function calls quack() directly on the object without checking its type. Python raises an error only if the method does not exist. This is duck typing.
What happens if the object does not have quack()?
As shown in step 7, Python raises an AttributeError because the method is missing.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result after calling quack on the Duck instance?
AAttributeError
B"Hello"
C"Quack!"
DNone
💡 Hint
Check row 3 in execution_table where quack is called on Duck.
At which step does the function detect the object lacks the quack method?
AStep 2
BStep 6
CStep 4
DStep 7
💡 Hint
Look at the check for quack method on the string object in execution_table.
If we pass an object with a quack method that returns "Meow", what would be the output?
A"Meow"
B"Quack!"
CAttributeError
DNone
💡 Hint
Duck typing calls the method on the object, so output matches the method's return.
Concept Snapshot
Duck typing means using any object that has the needed method.
No need to check object type explicitly.
If method exists, call it; else error occurs.
Python trusts the object's behavior, not its class.
This allows flexible and simple code.
Full Transcript
Duck typing in Python means that a function or method uses an object if it has the required method or behavior, regardless of the object's type. For example, a function make_it_quack calls quack() on any object passed to it. If the object has quack(), it works fine and returns the result. If not, Python raises an AttributeError. This approach trusts the object's capabilities rather than its class, making code flexible and simple.

Practice

(1/5)
1. What does duck typing in Python primarily focus on?
easy
A. Using only built-in Python types for safety
B. Checking the exact type of an object before using it
C. Using an object based on its methods and behavior, not its type
D. Restricting objects to a specific class hierarchy

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    Using an object based on its methods and behavior, not its type -> Option C
  4. Quick 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
A. def quack(duck): if hasattr(duck, 'quack'): duck.quack() class Duck: def quack(self): print('Quack!') quack(Duck())
B. def quack(duck: Duck): duck.quack() class Duck: def quack(self): print('Quack!') quack(Duck())
C. def quack(duck): if type(duck) == Duck: duck.quack() class Duck: def quack(self): print('Quack!') quack(Duck())
D. def quack(duck): duck.quack() class Duck: def quack(self): print('Quack!') quack(Duck())

Solution

  1. Step 1: Identify duck typing usage

    Duck typing means using an object if it has the needed method, without checking its type.
  2. Step 2: Analyze each option

    def quack(duck): if hasattr(duck, 'quack'): duck.quack() class Duck: def quack(self): print('Quack!') quack(Duck()) uses hasattr to 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.
  3. Final Answer:

    Using hasattr to check method presence before calling -> Option A
  4. Quick 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
A. Flying\nJet flying
B. Jet flying\nFlying
C. Flying\nFlying
D. Error: fly method not found

Solution

  1. Step 1: Understand the objects and their fly methods

    Bird has fly() printing 'Flying', Airplane has fly() printing 'Jet flying'.
  2. Step 2: Trace the loop calling fly on each object

    First object is Bird(), prints 'Flying'. Second is Airplane(), prints 'Jet flying'.
  3. Final Answer:

    Flying\nJet flying -> Option A
  4. Quick 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
A. No error, code runs fine
B. Add a sound() method to Cat class
C. Use type checking before calling sound()
D. Change animal.sound() to animal.meow()

Solution

  1. Step 1: Identify the method called on the object

    Function calls animal.sound(), but Cat class has meow(), not sound().
  2. Step 2: Fix the method call to match Cat's method

    Change animal.sound() to animal.meow() to call the existing method.
  3. Final Answer:

    Change animal.sound() to animal.meow() -> Option D
  4. Quick 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
A. Check if type(item) == Serializer before calling serialize()
B. Use if hasattr(item, 'serialize'): before calling item.serialize()
C. Wrap item.serialize() call in try-except to catch AttributeError
D. Define a base class with serialize() and inherit all objects from it

Solution

  1. Step 1: Understand duck typing safety

    Duck typing uses behavior, so checking method presence with hasattr is a safe way to confirm before calling.
  2. Step 2: Compare options for best practice

    Use if hasattr(item, 'serialize'): before calling item.serialize() checks method presence explicitly, fitting duck typing. Wrap item.serialize() call in try-except to catch AttributeError uses try-except but is less clear and may hide other errors. Check if type(item) == Serializer before calling serialize() checks type, which is not duck typing. Define a base class with serialize() and inherit all objects from it requires inheritance, reducing flexibility.
  3. Final Answer:

    Use if hasattr(item, 'serialize') before calling item.serialize() -> Option B
  4. Quick 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