Closures and Capture Timing
Lesson 25 of 48 in Coddy's Python for Rust Developers course.
Rust closures infer capture modes and can use move to take ownership of captured values. Python closures look up captured bindings when called, unless you explicitly snapshot a value, for example in a default parameter. The Python example shows a late-bound name and a default evaluated when the lambda is created. Rust move copies a captured Copy integer into the closure, so shadowing a later binding does not change that stored value. A Python lambda has one expression and returns it.
Rust excerpt inside main
let factor = 2;
let snapshot = move |x| x * factor;
let factor = 3;
println!("{} {}", snapshot(4), factor * 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
A default-argument snapshot stores an object reference, not a deep copy. If it captures a mutable list, later mutation of that list remains visible.
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 Rust Developers
1From Rust to Python
Run Your First Python ProgramMacros to printBindings, mut, and ShadowingIntegers and Floor DivisionIndentation and ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Borrowed Iteration to forEntries and enumeratewhile, break, and continueIterators and ComprehensionsRecap: Build a Ranking2Values and Decisions
Option and NoneEquality and Object IdentityTruth Tests and FallbacksIf Expressions and elifRecap: Eligibility Rules5Functions and Closures
Functions and Shared ObjectsNamed Arguments and DefaultsPacking Calls and OptionsClosures and Capture TimingRecap: Refactor a Pricing Tool3Ownership and Collections
Vec to listTuples and DestructuringHashMap to dictClone and Shallow CopiesRecap: Clean an Inventory6Errors and Modules
Text Input and FormattingResult, Exceptions, and withModules and the Main GuardHints Without Borrow CheckingRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler