Virtual Calls and Duck Typing
Lesson 40 of 48 in Coddy's Python for C++ Developers course.
C++ virtual dispatch usually uses a common base interface for heterogeneous runtime objects; templates can instead accept types satisfying operations at compile time. Python can call render(text) on unrelated classes at runtime without a shared base. This is duck typing: the needed behavior is the contract. The caller preserves encounter order and lets each object choose its implementation. Missing methods fail when used rather than at C++ template instantiation or compilation.
C++17 excerpt: inside main
Standard-library headers are supplied in the runnable companion program.
struct Renderer {
virtual std::string render(const std::string& text) const = 0;
virtual ~Renderer() = default;
};
struct Plain : Renderer {
std::string render(const std::string& text) const override { return text; }
};
struct Bracketed : Renderer {
std::string render(const std::string& text) const override { return "[" + text + "]"; }
};
Plain plain;
Bracketed bracketed;
std::vector<const Renderer*> renderers{&plain, &bracketed};
for (const auto* r : renderers) std::cout << r->render("hi") << '\n';Python
class Plain:
def render(self, text):
return text
class Bracketed:
def render(self, text):
return "[" + text + "]"
for renderer in [Plain(), Bracketed()]:
print(renderer.render("hi"))Porting trap
A chain of type checks is unnecessary here and would reject a new renderer supplied by the driver. Call the required method on each supplied object.
Implement the task below in its editable Python modules. The locked driver.py supplies execution and checks. Keep the specified imports and API names.
Challenge
BeginnerImplement Plain.render(text) returning text unchanged, Bracketed.render(text) returning text between [ and ], and render_all(renderers, text) returning a list of results in order. Both classes have no required constructor arguments. Input has a text line, a space-separated renderer-name line (possibly empty), and a prefix line. Renderer names are plain, bracket, exclaim, or probe. The locked driver supplies the last two classes; exclaim adds !, while probe adds the prefix. It prints one line per result, then calls:N for the probe call count. Each listed renderer must be called exactly once with the original text, including repeated names. The driver checks the probe's received arguments. Empty renderer lists return no results and print only calls:0. Do not inspect class names or require a shared base class. Submit the required class and function definitions only; input and printing belong to the locked driver.
Your code goes in the editable files plain.py and bracketed.py and functions.py. driver.py holds the supplied input/output code and API checks and cannot be edited. Keep the supplied imports; do not read input or print from the editable modules.
Try it yourself
from plain import Plain
from bracketed import Bracketed
from functions import render_all
class Exclaim:
def render(self, text):
return text + "!"
class Probe:
def __init__(self, prefix):
self.prefix = prefix
self.calls = []
def render(self, text):
self.calls.append(text)
return self.prefix + text
text = input()
names = input().split()
probe = Probe(input())
objects = {"plain": Plain(), "bracket": Bracketed(), "exclaim": Exclaim(), "probe": probe}
result = render_all([objects[name] for name in names], text)
for value in result:
print(value)
assert probe.calls == [text] * names.count("probe"), "Call each probe once with the original text"
print(f"calls:{len(probe.calls)}")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for C++ Developers
1From C++ to Python
Run Your First Python ProgramStreams to printNames, auto, and constDivision and Integer RangeBlocks and Name ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Range Loops and RebindingEntries and enumerateLoop Control Without ++Algorithms and ComprehensionsRecap: Build a Ranking2Values and Decisions
None, nullptr, and boolValues, Addresses, IdentityTruth Tests and OperandsBranches and Value SelectionRecap: Eligibility Rules5Functions, Calls, and Closures
Functions and Shared ObjectsDefaults and Named ArgumentsPacking and Unpacking CallsClosures and Capture TimingRecap: Refactor a Pricing Tool8Composition and Dispatch
Composition Without Value CopyInheritance and Method LookupVirtual Calls and Duck TypingEquality Beyond operator==Recap: Notification Channels3STL Habits and Python Objects
From vector to listTuples and Structured BindingsMaps, Keys, and OrderingValue Copies and Shared ListsRecap: Clean an Inventory6Errors, Resources, and Modules
Text Input and Exact OutputExceptions and RAIIModules Instead of HeadersHints Are Not Static TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler