Closures and Callable Values
Lesson 25 of 48 in Coddy's Python for Go Developers course.
Go functions are first-class values, and Python functions are too. A Python lambda is limited to one expression, whose value becomes its return; use def for statements or multi-step logic. Both examples read the current captured or surrounding binding when called. In a Python function, assigning a name makes it local unless declared global or nonlocal. Reading that local before assigning raises UnboundLocalError.
Go
Go excerpt inside main; imports: fmt. The verification bundle contains the complete program.
// Inside main:
offset := 3
f := func(n int) int { return n + offset }
fmt.Println(f(2))
offset = 7
fmt.Println(f(2))Python
offset = 3
f = lambda n: n + offset
print(f(2))
offset = 7
print(f(2))Porting trap
Python closures do not automatically snapshot loop variables. For a fresh snapshot in a callback, bind a default such as lambda n, saved=offset: n + saved. Go loop-variable behavior depends on language version and declaration form; do not infer Python capture from a Go loop.
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. As with a Go function-valued callback, invoke the supplied Python callable rather than choosing your own transformation.
Editable files: 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 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 Go Developers
1From Go to Python
Run Your First Python ProgramPrinting, Quotes, and CommentsBindings Beyond Go TypesDivision and Growing IntegersIndentation and ScopeRecap: A Python Receipt4Iteration and Transformations
range and Value IterationIndexes and Map EntriesSentinels Without Truth TrapsComprehensions and Stable SortRecap: Stable Ranking2Values, Absence, and Branches
None, nil, and Zero ValuesEquality Is Not IdentityTruth Tests Beyond boolBranches and Value SelectionRecap: Missing or Eligible5Functions and Call Contracts
Functions and Tuple ReturnsDefaults and Named ArgumentsVariadics and Keyword OptionsClosures and Callable ValuesRecap: Pricing Functions3Slices, Maps, and Sharing
Slices Versus Python ListsMultiple Values and TuplesGo Maps and Python dictsSets and Shallow CopiesRecap: Inventory Collections6Errors, Modules, and Hints
Text and Exact OutputErrors Versus ExceptionsPackages and Module ExecutionHints Versus Static TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler