Menu
CoddyTech

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 icon

Challenge

Beginner

Implement 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)}")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for Java Developers

Practice on your own: Online Python compiler