Arrow Capture and Late Binding
Lesson 25 of 48 in Coddy's Python for PHP Developers course.
PHP arrow functions capture outer variables by value. PHP closures can use use ($x) for value capture or use (&$x) for a reference. Python closures look up outer bindings when called, not when created. A Python lambda contains one expression and follows the same lookup rule as a nested def. To retain a current loop value, a default parameter such as lambda n=n: n can capture it at definition time.
PHP 8.3
<?php
$factor = 2;
$scale = fn($x) => $x * $factor;
$factor = 3;
echo $scale(4), "\n";Python
factor = 2
scale = lambda x: x * factor
factor = 3
print(scale(4))Porting trap
Python assignment inside a function makes a name local unless declared otherwise. Use nonlocal to rebind an enclosing function's name; reading it does not require a declaration. Module bindings use global for rebinding.
Complete the task in the editable Python files. Keep the required function and class names; the locked driver.py supplies execution.
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 PHP Developers
1From PHP to Python
Run Your First Python ProgramEcho, Strings, and printVariables Without Dollar SignsDivision and Numeric TextIndentation and SuitesRecap: Rewrite a Receipt4Iteration and Transformations
Foreach and rangeKeys, Items, and enumerateWhile Without IncrementFilters and Sort KeysRecap: Build a Ranking2Values and Decisions
Null, None, and Missing KeysStrict Equality Is Not isThe Zero String TrapElif and Value SelectionRecap: Eligibility Rules5Functions and Closures
Functions and Mutable InputsNamed Calls and Default StateVariadics and Call UnpackingArrow Capture and Late BindingRecap: Refactor a Pricing Tool3Arrays and Python Collections
PHP Arrays and Python ListsDestructuring and TuplesKeys, Null, and getArray Copies and List AliasesRecap: Clean an Inventory6Input, Errors, and Modules
CLI Input and Exact OutputConversion Errors and CleanupImports Instead of requireType Hints Are Not PHP TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler