Generics to Duck Typing
Lesson 40 of 48 in Coddy's Python for R Developers course.
R generic functions such as print dispatch according to object class. Python can instead call the same method name on unrelated objects, relying on a shared behavioral contract. This duck typing does not require an explicit common base. Each renderer must accept text and return text, regardless of its concrete class. R S3 method registration and Python receiver lookup are different mechanisms even when the visible results agree. Importing a Python module does not register R-style generic methods automatically. Keep type-specific details inside the implementations so callers need not branch on class names.
R
render <- function(x, text) UseMethod("render")
render.plain <- function(x, text) text
render.bracketed <- function(x, text) paste0("[", text, "]")
for (kind in c("plain", "bracketed")) {
x <- structure(list(), class=kind)
cat(render(x, "hi"), "\n", sep="")
}Python
class Plain:
def render(self, text):
return text
class Bracketed:
def render(self, text):
return f'[{text}]'
for renderer in [Plain(), Bracketed()]:
print(renderer.render('hi'))Porting trap
A shared method name is insufficient if argument or return contracts differ. Polymorphic callers depend on compatible behavior.
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 R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules5Functions and Environments
Explicit Function ReturnsLazy and Eager DefaultsDots Versus Star ArgumentsEnvironments and nonlocalRecap: Refactor a Pricing Tool8Composition and Dispatch
Store a CollaboratorNextMethod and superGenerics to Duck TypingRecords and Generated EqualityRecap: Notification Channels3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler