Interfaces and Duck Typing
Lesson 40 of 48 in Coddy's Python for Go Developers course.
Go interfaces are satisfied implicitly by method sets; there is no implements declaration. The compiler checks whether a value assigned to an interface provides its methods, with pointer and value method-set differences. Python duck typing similarly focuses on available behavior, but an ordinary call discovers a missing method at runtime. Optional typing.Protocol can express a structural contract for a type checker; it is not needed for this task.
Go
Go excerpt: declarations above main, statements inside main. Imports: fmt. The verification bundle contains the complete program.
type Renderer interface { Render(string) string }
type Plain struct{}
func (Plain) Render(s string) string { return s }
type Bracketed struct{}
func (Bracketed) Render(s string) string { return "[" + s + "]" }
// Inside main:
items := []Renderer{Plain{}, Bracketed{}}
for _, r := range items { fmt.Println(r.Render("hi")) }Python
class Plain:
def render(self, text):
return text
class Bracketed:
def render(self, text):
return "[" + text + "]"
for r in [Plain(), Bracketed()]:
print(r.render("hi"))Porting trap
Call each renderer once, in order, including repeats. Do not switch on concrete class names. A previously unseen object with the required render method should work. Missing methods raise AttributeError; a wrong call signature may raise TypeError.
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. Go interfaces are implicit but statically checked; these Python calls need the required methods without a shared base class.
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 Go Developers
1From Go to Python
Run Your First Python ProgramPrinting, Quotes, and CommentsBindings Beyond Go TypesDivision and Growing IntegersIndentation and ScopeRecap: A Python Receipt4Iteration and Transformations
range and Value IterationIndexes and Map EntriesSentinels Without Truth TrapsComprehensions and Stable SortRecap: Stable Ranking2Values, Absence, and Branches
None, nil, and Zero ValuesEquality Is Not IdentityTruth Tests Beyond boolBranches and Value SelectionRecap: Missing or Eligible5Functions and Call Contracts
Functions and Tuple ReturnsDefaults and Named ArgumentsVariadics and Keyword OptionsClosures and Callable ValuesRecap: Pricing Functions8Interfaces and Object Design
Interface Fields and CallsEmbedding Is Not InheritanceInterfaces and Duck TypingStructs and Data ClassesRecap: Pluggable Channels3Slices, Maps, and Sharing
Slices Versus Python ListsMultiple Values and TuplesGo Maps and Python dictsSets and Shallow CopiesRecap: Inventory Collections6Errors, Modules, and Hints
Text and Exact OutputErrors Versus ExceptionsPackages and Module ExecutionHints Versus Static TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler