Lesson · Object-Oriented Python
Polymorphism & Duck Typing
55 min readPolymorphism & Duck Typing
Duck typing asks whether an object supports the behavior you need rather than whether it has a specific concrete type. This is one of the reasons Python APIs can remain small and flexible.
Learning goals
- Explain duck typing as "the call works if the object supports the needed operation", using
emitand its two writer classes. - Describe what
emitrequires of its first argument and why neither writer needs a shared base class. - Predict what
emit(42, "x")raises and read theAttributeErroras a missing behavior. - Separate behavioral compatibility from matching method names: the same call has to mean the same thing.
- State the implicit contract in the example (
write(value)accepts one value and returns something printable) and where it is documented.
Mental model
The requirement travels with the call, not with a class hierarchy: whatever object arrives only needs to answer write(value) with a usable result. When the expectation is written down rather than enforced, it is an informal interface, and both writers satisfy it independently.
Mental model
read it top to bottom
caller runs emit(writer, value) ↓ what does the call require? a write method that accepts value and returns something printable ↓ satisfied by JsonWriter, TextWriter, or any object with that behavior no shared base class needed; the expectation lives in documentation
Core idea
Polymorphism means one piece of code accepting several object types, and duck typing is how Python gets there without inheritance: emit calls writer.write(value) and works for anything that answers that call. The interface is the set of operations the code performs, so the type check disappears and the contract moves into the operation names and their expected results. Two objects can match on names and still be incompatible if the behavior differs, which is why the contract, not the signature list, is the real interface.
Behavioral compatibility
Behavioral compatibility means an object satisfies the operations and semantics the caller relies on. Merely having methods with the same names is not enough if their contracts differ.
Duck typing
Duck typing focuses on supported behavior rather than concrete ancestry. If an object provides the operations an algorithm needs, the algorithm can often use it without a shared base class.
Informal interfaces
An informal interface is a documented set of expected behaviors without a required base class. Python libraries often rely on this style of duck typing.
Polymorphism without inheritance
Polymorphism without inheritance means several unrelated classes satisfy the same call because each defines the operation the caller uses; JsonWriter and TextWriter share no base class yet both answer write. The code that loops or dispatches over them never mentions their types, which keeps new writers additive rather than invasive. The price is that nothing enforces the shared shape at import time, so an incomplete writer fails only when the call reaches it.
Protocol-based thinking
Protocol-based thinking asks what operations syntax requires—iteration, containment, length, context management—rather than which concrete class the object inherits from.
Walkthrough
JsonWriter.writereturnsf"json:{value}"andTextWriter.writereturnsstr(value); both accept one value and return a string, soemitcan call either one the same way.emit(writer, value)never names a writer class:writer.write(value)is the only requirement, and Python resolves it at call time against whatever object was passed.- The first print shows
json:{'x': 1}(the dict is interpolated into the f-string, not JSON-encoded) and the second shows42as a string; neither class inherits from the other or from a shared interface. - Predict before running: both printed lines, what
emit(42, "x")raises, and which operation the call was missing when it failed.
Experiments to try
- Call
emit(42, "x"), read theAttributeError, and explain that the failure is a missingwriteoperation rather than a type mismatch. - Add
class ListWriterwith awritethat returns[value]and confirmemitaccepts it with no changes; state the requirement it satisfied. - Give
TextWriter.writea second parameter without a default and rerunemit; read theTypeErrorand explain the difference between names matching and signatures matching. - Replace one writer's
writewith a plain string attribute (for examplewrite = "nope") and rerun; read theTypeErrorand say why it could only surface when the call executed.
Common mistakes
- Assuming same-named methods guarantee compatibility: two
writemethods can accept different arguments or return different kinds of value, and the mismatch surfaces only when the caller uses the result. - Guarding a duck-typed call with
isinstance(writer, JsonWriter): the check rejects valid objects such asTextWriterand couplesemitto a class it never otherwise needs. - Confusing the method list with the contract: an object can define
writeand still returnNone, so code that expects a printable string breaks on the result rather than the call. - Documenting nothing: Python cannot enforce an informal interface, so if three modules expect
writeto mean three different things, duck typing turns into guesswork; write the expected behavior down.
Practice: Easy
- Run the worked example and record both printed strings; note that
{"x": 1}was formatted into text by the f-string rather than encoded as JSON. - Call
emit(JsonWriter(), "hello")andemit(TextWriter(), {"x": 1}); predict each output before running and explain why both writers accept both values. - Rename both writers'
writetorenderand run the example; read theAttributeErrorand state exactly which name the caller needed.
Practice: Medium
- Add a
NullWriterwhosewriteraisesValueErrorfor values it does not support; callemitwith a rejected value and decide whether refusing in the writer or at the call site keepsemithonest. - Write
emit_all(writer, values)that callswriter.writein a loop; test it with both writers and explain why the function needs no knowledge of either class. - Implement the same behavior twice, once as two unrelated classes and once with a shared base class; argue which version is easier to extend and which is easier to type-check upfront.
Practice: Hard
- Design a small rendering toolkit where
render(writer, items)requireswrite(value)andfinish()from the writer. Document the informal interface in a docstring, then implement two writers and one deliberately incomplete writer with tests. - Build a failure lab: a writer whose
writereturnsNone, awriteattribute that is not callable, and a writer whose signature drifted. Show the exact error each produces and the moment it appears. - Connect this lesson to the abstract base classes lesson: register one of your writers against an ABC and explain what the ABC adds (early errors, documentation) and what it cannot check (the meaning of the returned value).
Lesson checklist
- I can state
emit's requirement as a behavior rather than a type. - I can explain why
JsonWriterandTextWriterneed no shared base class. - I can read the
AttributeErrorfromemit(42, "x")as a missing operation. - I can give an example where matching method names still break behavioral compatibility.
Remember
Duck typing shifts the interface from classes to operations: `emit` works with any object whose `write` accepts a value, which is why unrelated writers compose without a base class. The contract is informal, so naming the expected behavior and satisfying it consistently is what keeps the flexibility from turning into guesswork; matching names alone is not compatibility.
Interview angles
What is the main purpose of **Behavioral compatibility**?+
Behavioral compatibility means an object satisfies the operations and semantics the caller relies on. Merely having methods with the same names is not enough if their contracts differ.
What should you pay attention to when using **Duck typing**?+
Duck typing focuses on supported behavior rather than concrete ancestry. If an object provides the operations an algorithm needs, the algorithm can often use it without a shared base class.
How does **Informal interfaces** fit into this lesson?+
An informal interface is a documented set of expected behaviors without a required base class. Python libraries often rely on this style of duck typing.
Why does adding `isinstance(writer, JsonWriter)` make a duck-typed function worse, not safer?+
A concrete type check rejects any other object that already answers the needed call, so a valid writer like TextWriter fails for the wrong reason. It also couples the function to a class it never otherwise mentions, and the real requirement, a write method with the expected behavior, is better stated in a docstring or protocol.