Capture Lists and Defaults
Lesson 25 of 48 in Coddy's Python for Swift Developers course.
Swift closures can use capture lists to snapshot values and can otherwise capture surrounding variables. Python closures look up captured bindings when called; a default argument can snapshot the current object at function creation. In both languages, capturing a reference to a mutable object does not deep-copy its contents. Python lambda supports one expression, while def is used for multi-statement functions. A nested Python function needs nonlocal to rebind an enclosing function's variable.
Swift example
var factor = 2
let f = { (x: Int) in x * factor }
let snapshot = { [factor] (x: Int) in x * factor }
factor = 3
print(f(4), snapshot(4))Python
factor = 2
f = lambda x: x * factor
snapshot = lambda x, factor=factor: x * factor
factor = 3
print(f(4), snapshot(4))Porting trap
Swift weak and unowned capture controls do not have direct Python lambda syntax. Python lifetime and cycle handling are a different runtime model.
Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.
Challenge
BeginnerImplement transform_all(values, transform). Call the supplied one-argument function exactly once per list element, in encounter order, and return a new list of its results. Preserve values. Do not print. The locked driver reads integer tokens on one line. It calls your function with two different callbacks: adding 3 and negating. It prints both result lists, then both callback counts on one line. Next it prints True if both callbacks received exactly the original elements in order, and finally unchanged or changed for the input list.
Your function definitions go in functions.py. The locked driver.py imports them and handles the supplied input/output and checks. You do not need to edit the driver.
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 Swift Developers
1From Swift to Python
Run Your First Python ProgramPrinting and Stringslet, var, and RebindingInt Range and DivisionIndentation and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for and Half-Open Rangesenumerated to enumeratewhile and Loop Controlmap, filter, ComprehensionsRecap: Build a Ranking2Values and Decisions
Optionals and NoneEquatable and IdentityBool Conditions and FallbacksBranches and TernariesRecap: Eligibility Rules5Functions and Closures
Functions and Explicit ReturnArgument Labels and DefaultsVariadics and Call ExpansionCapture Lists and DefaultsRecap: Refactor a Pricing Tool3Value Types to Shared Objects
Array to listTuples and UnpackingDictionary Lookup and OrderValue Copies and AliasesRecap: Clean an Inventory6Errors and Modules
Input and String Formattingthrows, defer, and withModules and Main GuardsHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler