Callbacks and Captured Names
Lesson 25 of 48 in Coddy's Python for C Developers course.
C can pass a function pointer, but an ordinary C function pointer does not carry a captured environment. A callback API often adds a separate context pointer. Python function objects can refer to names in surrounding scopes. A lambda is a function defined by one expression; it returns that expression automatically. Closures generally look up captured names when called, so rebinding factor before the call changes this result. Callback consumers should call once per item and preserve order unless their contract says otherwise.
C: complete example.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int twice(int value) { return value * 2; }
int main(void) {
int (*transform)(int) = twice;
printf("%d\n", transform(4));
return 0;
}Python: complete example.py
factor = 2
transform = lambda value: value * factor
factor = 3
print(transform(4))Watch the difference
A Python assignment inside a function normally creates a local name. Use nonlocal only when deliberately rebinding a name in an enclosing function scope. Mutating an existing captured list does not require nonlocal.
Your code goes in functions.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
Challenge
BeginnerImplement transform_all(values, transform): call the callback once for each original element in order and return a fresh result list. Preserve the input list. The driver uses addition-by-three and negation callbacks, prints both results and call counts, reports argument-order correctness, then prints unchanged or changed.
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.
A Python callable can retain context, whereas C callbacks often pair a function pointer with a separate context pointer.
Your code goes in functions.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
Try it yourself
from functions import transform_all
values = [int(part) for part in input().split()]
before = values.copy()
plus_calls = []
negative_calls = []
def plus(value):
plus_calls.append(value)
return value + 3
def negative(value):
negative_calls.append(value)
return -value
print(transform_all(values, plus))
print(transform_all(values, negative))
print(len(plus_calls), len(negative_calls))
print(plus_calls == before and negative_calls == before)
print("unchanged" if values == before else "changed")
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 Functions3Containers 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