One save() call, three exporters: polymorphism and duck typing in Python.
In one line
One method name, different behavior for each object. Python checks whether an object has the method rather than which class it belongs to (duck typing), so you get this without inheritance too.
Why you need it
If every new export format (CSV, JSON, Excel) adds another if fmt == ... line, you must edit every function that has that chain. Miss one, and that format quietly breaks.
Give each format its own class with a method of the same name, and the calling code stays one line: t.save(row). A new format is one new class.
Everyday picture
Think of a wall socket. The wall does not know whether a fan or a phone charger is plugged in; if the plug fits, it supplies power, and each device does its own thing. The plug shape is the method name, the devices are the objects.
Example code
main.py · 39 lines
import jsonclassExporter: label = "base"defexport(self, row):raiseNotImplementedErrordefsave(self, row):returnf"[{self.label}] {self.export(row)}"classCsvExporter(Exporter): label = "csv"defexport(self, row):return",".join(str(v) for v in row.values())classJsonExporter(Exporter): label = "json"defexport(self, row):return json.dumps(row)classLineLogger: label = "line"defsave(self, row):returnf"[{self.label}] " + " ".join(f"{k}={v}"for k, v in row.items())row = {"name": "kim", "age": 31}targets = [CsvExporter(), JsonExporter(), LineLogger()]for t in targets:print(t.save(row))print([isinstance(t, Exporter) for t in targets])
Press Run to try your edited code right away. The step-through and the output above follow the original code.
When to use it
There are several ways to do the same job (file formats, payment methods, notification channels)
The same if type(x) is ... check appears in several functions
Tests should pass in a fake object that has the same methods as the real one
Duck typing is convenient, but a missing method only shows up when the code runs. To demand certain methods up front, use an abstract base class (next topic) or typing.Protocol.
Common mistakes
Branching on the class with if chains
Every new format (Xml) means hunting down the if chain, and if you forget, you silently get None. Move the behavior into each class as a method, and adding a format means adding a class.
Duck typing checks nothing up front. The string "json" has no save, and the error only appears when the loop reaches it. Keep the list to objects with the same method.
Wrong
row = {"name": "kim", "age": 31}for t in [CsvExporter(), "json"]:print(t.save(row))
When you run itAttributeError: 'str' object has no attribute 'save'
Fixed
row = {"name": "kim", "age": 31}for t in [CsvExporter(), JsonExporter()]:print(t.save(row))
When you run it[csv] kim,31
[json] {"name": "kim", "age": 31}
Check yourself
Question 1
Robot does not inherit from Exporter. Can it join the same loop if it has save(row)?
classRobot: label = "bot"defsave(self, row):returnf"[{self.label}] {len(row)} fields"for t in [CsvExporter(), Robot()]:print(t.save({"a": 1, "b": 2}))
Show the answer
Answer: 1. Yes, it has `save(row)` The loop only calls t.save(row). Any class with that method works. That is duck typing.
Question 2
What does JsonExporter().save({"x": 1}) return?
print(JsonExporter().save({"x": 1}))
Show the answer
Answer: 2. [json] {"x": 1}save comes from the parent, but self.label is looked up on the object's class first, so it is json.
Questions people ask
What is duck typing?
Ignoring an object's class and checking only that it has the method you need. Anything with save() can take the same place in the code.
Does polymorphism work without inheritance?
Yes. Python calls the method by name, so matching names are enough. Add inheritance when you also want to share code.
Is checking with isinstance wrong?
It works, but once you branch on classes with if, every new class means more edits. Keep the behavior in each class's own method.