Interfaces and Duck Typing
Lesson 40 of 48 in Coddy's Python for Java Developers course.
Write clients against behavior. Java nominal interfaces require classes to declare implements; these Python renderers cooperate because each offers a compatible render method. A client can loop over objects and call that method without checking class names. This permits a caller-supplied implementation unknown when the client was written. Duck typing does not verify argument counts or result types ahead of time: incompatible calls fail when executed. Optional Protocol annotations can describe structural contracts to static tools, but are not required for these exercises.
Java excerpt: class member declarations
// Class members
interface Renderer { String render(String text); }
static class Plain implements Renderer {
public String render(String text) { return text; }
}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"))Watch the difference
Do not replace a method call with an if chain for Plain and Bracketed. That rejects new implementations. Call once per item with the original argument; callbacks may record calls, so duplicated work is observable.
Practice
Apply this comparison in the task below. Editable files: plain.py, bracketed.py, functions.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.
Challenge
BeginnerImplement Plain.render(text) returning text, Bracketed.render(text) adding square brackets, and render_all(renderers,text) returning one result per renderer in order. Both classes take no required constructor arguments. Input contains text, renderer names (possibly none), and a prefix. The driver supplies exclaim and probe renderers in addition to plain and bracket, prints results then calls:N, and verifies original arguments and exactly one call per listed renderer, including repeats. Empty lists print calls:0 only. Unlike Java nominal interfaces, no shared Python base class is required.
Editable files: plain.py, bracketed.py, functions.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.
Implement the named definitions in the editable modules without input or printing. The driver owns input/output and may call the APIs again on fresh data without producing extra output.
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 Java Developers
1From Java Classes to Python
Run Python Without a ClassPrinting Text and CommentsBindings, Types, and finalDivision and Numeric TypesIndentation Defines BlocksRecap: A Python Receipt4Iteration and Transformations
Enhanced Loops and rangeIndexes and Map EntriesSentinels and Loop ControlFrom Streams to ComprehensionsRecap: Stable Ranking2Values Beyond Java Primitives
None and Boolean ValuesValue Equality and IdentityTruth Tests Beyond booleanBranches and Value SelectionRecap: Missing or Eligible5Functions Beyond Methods
Functions Outside ClassesDefaults Instead of OverloadsVarargs and Keyword OptionsScope and Callable ObjectsRecap: Pricing Functions8Behavior Beyond Interfaces
Collaborators Without CastsInheritance and InitializationInterfaces and Duck TypingRecords and Data ClassesRecap: Pluggable Channels3Collections and Object Sharing
Lists and ArrayList HabitsTuples Without Record ClassesDictionaries and Java MapsShared References and CopiesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputValueError and TypeErrorModules Versus Utility ClassesAnnotations Are Not Java TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler