Closures and nonlocal
Lesson 25 of 48 in Coddy's Python for Dart Developers course.
Both languages have first-class functions and closures that retain access to surrounding bindings. Dart closures can update a captured local directly. Python nested functions need nonlocal to rebind an enclosing function variable; otherwise assignment makes it local to the nested function. Python global targets module scope instead. A Python lambda is limited to one expression, so use def for multi-statement callbacks or state updates. Function values can be passed without invoking them. Captured state survives after the outer function returns, which allows a returned counter callback to remember previous calls.
Dart
int Function() counter() {
var count = 0;
return () => ++count;
}
void main() {
final increment = counter();
print(increment());
print(increment());
}Python
def counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
increment = counter()
print(increment())
print(increment())Porting trap
A direct captured-variable assignment from Dart may cause an unbound-local error in Python unless nonlocal is declared.
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 Dart Developers
1From Dart to Python
Run Your First Python ProgramInterpolation and printvar, final, and Python NamesFloor Versus TruncationBraces and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for-in and rangeentries and enumerateLoop Updates and continuewhere, map, and List BuildingRecap: Build a Ranking2Values and Decisions
Null Safety and NoneList Equality ChangesConditions and Null DefaultsTernaries and elifRecap: Eligibility Rules5Functions and Closures
Arrows and Explicit ReturnsNamed Calls and DefaultsExplicit Variadic ArgumentsClosures and nonlocalRecap: Refactor a Pricing Tool3Collections and References
Lists and Negative IndexesRecords and Tuple UnpackingMap Lookups and KeyErrorSets and Shared ObjectsRecap: Clean an Inventory6Reliable Python Programs
stdin and Exact Formattingon, catch, finally, and withLibraries and Import ExecutionStatic Types Versus HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler