Behavior Without Vtables
Lesson 40 of 48 in Coddy's Python for C Developers course.
A C program can define a function-pointer table with a compatible signature and dispatch through that table. Python can call a method with the expected name on each object without requiring a declared common superclass. This is duck typing: the usable behavior is what matters to the consumer. Keep the call count, original argument, and result order required by the contract. The Python render methods return strings; the loop owns printing, whereas the compact C callback example prints inside each callback.
C: complete example.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
struct Renderer { void (*render)(const char *); };
void plain(const char *text) { puts(text); }
void bracket(const char *text) { printf("[%s]\n", text); }
int main(void) {
struct Renderer items[] = {{plain}, {bracket}};
for (int i = 0; i < 2; ++i) items[i].render("hi");
return 0;
}Python: complete example.py
class Plain:
def render(self, text):
return text
class Bracket:
def render(self, text):
return "[" + text + "]"
for renderer in [Plain(), Bracket()]:
print(renderer.render("hi"))Watch the difference
Do not branch on concrete class names to select behavior. That rejects a new renderer that already implements render correctly. Missing methods or incompatible calls still fail at runtime; duck typing does not make every object suitable.
Your code goes in plain.py, bracketed.py, functions.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
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.
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.
C can dispatch through compatible function pointers; Python dispatches through each supplied render method without a required base class.
Your code goes in plain.py, bracketed.py, functions.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
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 C Developers
1From C Programs to Python
Run Python Without mainPrinting Without Format CodesNames Versus Typed StorageDivision and Integer LimitsSuites Instead of BracesRecap: A Python Receipt4Iteration and Transformations
Iteration Without PointersIndexes Without Pointer MathSentinels and Loop ControlComprehensions and SortingRecap: Stable Ranking2Values and Truth Tests
Absence Is Not a Null PointerContent Versus Object IdentityTruth Tests and OperandsConditional Value SelectionRecap: Missing or Eligible5Functions and Callbacks
Functions and Object ArgumentsDefaults and Named ArgumentsVarargs Without va_listCallbacks and Captured NamesRecap: Pricing Functions8Composition and Inheritance
Callbacks to CompositionEmbedding Versus InheritanceBehavior Without VtablesEquality and Data ClassesRecap: Pluggable Channels3Containers and Aliasing
Lists Versus C ArraysTuples and Struct ValuesMappings and Lookup LoopsPointers, Copies, and AliasesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputError Codes Versus ExceptionsImports Are Not IncludesAnnotations Versus C TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler