Traits and Duck Typing
Lesson 40 of 48 in Coddy's Python for Rust Developers course.
Rust generic trait bounds check a behavior contract statically, and trait objects such as &dyn Render support runtime dispatch through an explicit trait. Python can call a shared method on unrelated classes without a declared common base. That is duck typing: the caller depends on available behavior. The renderer loop preserves input order and asks each object to render. A missing method fails when used. Optional typing Protocols can describe structural contracts to a checker but are not required for this runtime call.
Rust excerpt inside main
trait Render { fn render(&self, text: &str) -> String; }
struct Plain;
struct Bracketed;
impl Render for Plain { fn render(&self, text: &str) -> String { text.to_owned() } }
impl Render for Bracketed { fn render(&self, text: &str) -> String { format!("[{}]", text) } }
let plain = Plain;
let bracketed = Bracketed;
let renderers: [&dyn Render; 2] = [&plain, &bracketed];
for renderer in renderers { println!("{}", renderer.render("hi")); }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 defeats this design: a new object with the required render method should work without editing the caller.
Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.
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 Rust Developers
1From Rust to Python
Run Your First Python ProgramMacros to printBindings, mut, and ShadowingIntegers and Floor DivisionIndentation and ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Borrowed Iteration to forEntries and enumeratewhile, break, and continueIterators and ComprehensionsRecap: Build a Ranking2Values and Decisions
Option and NoneEquality and Object IdentityTruth Tests and FallbacksIf Expressions and elifRecap: Eligibility Rules5Functions and Closures
Functions and Shared ObjectsNamed Arguments and DefaultsPacking Calls and OptionsClosures and Capture TimingRecap: Refactor a Pricing Tool8Composition and Dispatch
Composition and AliasesInheritance Beyond TraitsTraits and Duck TypingDerived Equality and DataclassRecap: Notification Channels3Ownership and Collections
Vec to listTuples and DestructuringHashMap to dictClone and Shallow CopiesRecap: Clean an Inventory6Errors and Modules
Text Input and FormattingResult, Exceptions, and withModules and the Main GuardHints Without Borrow CheckingRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler