Menu
CoddyTech

Closures and Capture Timing

Lesson 25 of 48 in Coddy's Python for C++ Developers course.

A Python function is a callable value that can be passed to another function. lambda creates a function containing one expression. Python closures look up captured bindings when called rather than providing a C++ [=] or [&] capture list. C++ value capture below keeps factor at 2; reference capture observes the later 3 while factor is alive. Python can capture a current value through a default parameter, such as lambda x, factor=factor: x * factor.

C++17 excerpt: inside main

Standard-library headers are supplied in the runnable companion program.

int factor = 2;
auto captured = [factor](int x) { return x * factor; };
auto referenced = [&factor](int x) { return x * factor; };
factor = 3;
std::cout << captured(4) << ' ' << referenced(4) << '\n';

Python

factor = 2
f = lambda x: x * factor
snapshot = lambda x, factor=factor: x * factor
factor = 3
print(f(4), snapshot(4))

Porting trap

Assigning to an enclosing function name requires nonlocal; changing a referenced list does not. Late binding also matters when building lambdas in a loop.

Implement the task below in its editable Python modules. The locked driver.py supplies execution and checks. Keep the specified imports and API names.

challenge icon

Challenge

Beginner

Implement 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")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for C++ Developers

Practice on your own: Online Python compiler