Interfaces and Duck Typing
Lesson 40 of 48 in Coddy's Python for PHP Developers course.
PHP can require an interface in a parameter type. Python ordinary code can instead call the required method on any object that provides it, even without a shared base class. This is duck typing. Keep the method signature and behavior consistent across collaborators. Type hints or protocols can document that contract for tools, but an ordinary unannotated function does not perform PHP interface enforcement.
PHP 8.3
<?php
interface Renderer { public function render($text); }
class Bracketed implements Renderer { public function render($text) { return '[' . $text . ']'; } }
function show(Renderer $renderer, $text) { return $renderer->render($text); }
echo show(new Bracketed(), 'hi'), "\n";Python
class Bracketed:
def render(self, text):
return f"[{text}]"
def show(renderer, text):
return renderer.render(text)
print(show(Bracketed(), "hi"))Porting trap
A missing method fails at runtime with AttributeError. Duck typing does not mean every object works; it means the operation depends on supported behavior rather than an explicit implements declaration.
Complete the task in the editable Python files. Keep the required function and class names; the locked driver.py supplies execution.
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 PHP Developers
1From PHP to Python
Run Your First Python ProgramEcho, Strings, and printVariables Without Dollar SignsDivision and Numeric TextIndentation and SuitesRecap: Rewrite a Receipt4Iteration and Transformations
Foreach and rangeKeys, Items, and enumerateWhile Without IncrementFilters and Sort KeysRecap: Build a Ranking2Values and Decisions
Null, None, and Missing KeysStrict Equality Is Not isThe Zero String TrapElif and Value SelectionRecap: Eligibility Rules5Functions and Closures
Functions and Mutable InputsNamed Calls and Default StateVariadics and Call UnpackingArrow Capture and Late BindingRecap: Refactor a Pricing Tool8Composition and Dispatch
Sharing CollaboratorsParent Calls and superInterfaces and Duck TypingEquality and DataclassesRecap: Notification Channels3Arrays and Python Collections
PHP Arrays and Python ListsDestructuring and TuplesKeys, Null, and getArray Copies and List AliasesRecap: Clean an Inventory6Input, Errors, and Modules
CLI Input and Exact OutputConversion Errors and CleanupImports Instead of requireType Hints Are Not PHP TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler