Interfaces and Duck Typing
Lesson 40 of 48 in Coddy's Python for C# Developers course.
Support unfamiliar objects through a shared behavioral contract.
C# reference excerpt
Executable statements use C# top-level program style; type-only examples are declarations. System names assume the usual using System directive.
interface IRenderer { string Render(string text); }
class Plain : IRenderer { public string Render(string text) => text; }
class Bracketed : IRenderer { public string Render(string text) => "[" + text + "]"; }Python
class Plain:
def render(self, text):
return text
class Bracketed:
def render(self, text):
return "[" + text + "]"
print(Bracketed().render("hi"))What changes
C# interface conversion normally depends on the declared implemented interface. Python code can call render on unrelated objects without a declared common base. The behavioral contract still matters: the method must accept the argument and return suitable text. typing.Protocol can describe structural contracts to optional static checkers, but is not required here and does not automatically validate calls at runtime.
Transfer mistake
Do not branch on class names to choose behavior. Calling each supplied renderer once lets unknown compatible objects participate. Missing methods fail at runtime, usually with AttributeError.
Your task
Implement Plain.render(text), returning unchanged text; Bracketed.render(text), wrapping it in [ and ]; and render_all(renderers, text), returning results in list order. Constructors take no required arguments. Input is text, a possibly empty renderer-token line, and a prefix. Tokens are plain, bracket, exclaim, or probe; the driver supplies the latter two. Call every listed renderer exactly once with the original text, including repeats. The driver prints each result then calls:N for probe invocations and checks received arguments. Empty lists print only calls:0. Do not require a base class or inspect class names.
Challenge
BeginnerImplement Plain.render(text), returning unchanged text; Bracketed.render(text), wrapping it in [ and ]; and render_all(renderers, text), returning results in list order. Constructors take no required arguments. Input is text, a possibly empty renderer-token line, and a prefix. Tokens are plain, bracket, exclaim, or probe; the driver supplies the latter two. Call every listed renderer exactly once with the original text, including repeats. The driver prints each result then calls:N for probe invocations and checks received arguments. Empty lists print only calls:0. Do not require a base class or inspect class names.
Editable implementation files: plain.py, bracketed.py, functions.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.
Keep the supplied imports and exact API names. Return results or raise the required exceptions; do not read input or print from these implementation 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
1C# Foundations in Python
Run the Python WorkspaceOutput, Strings, and CommentsTyped Locals to Python NamesDivision and RemaindersIndentation Instead of BracesRecap: Port a Receipt4Loops and Transformations
From foreach to forIndexes and Dictionary ItemsSentinels and Loop ControlFrom LINQ to ComprehensionsRecap: Stable Ranking2None and Decisions
Nullable Values and NoneEquality, Identity, and TypesTruth Tests and FallbacksBranch PriorityRecap: Eligibility Rules5Functions and Scope
Define Functions and ReturnNamed Arguments and DefaultsStar Arguments and UnpackingCallbacks and Python ScopeRecap: Pricing Functions8Composition and Inheritance
Replaceable CollaboratorsOverrides and superInterfaces and Duck TypingRecords and Value EqualityRecap: Dispatch by Behavior3Collections and References
From List<T> to listTuples and UnpackingDictionary Keys and ValuesSets, Aliases, and CopiesRecap: Stock Lookup6Reliable Python Programs
Input and Exact OutputExceptions and ValidationImports and the Main GuardType Hints and Runtime TypesRecap: Validate a Batch9Project: Order Processor
Project 1: Order ModelProject 2: Pricing PoliciesPractice on your own: Online Python compiler