Callbacks and Python Scope
Lesson 25 of 48 in Coddy's Python for C# Developers course.
Pass callbacks and distinguish local rebinding from object mutation.
C# reference excerpt
Executable statements use C# top-level program style; type-only examples are declarations. System names assume the usual using System directive.
Func<int, int> increment = x => x + 1;
Console.WriteLine(increment(4));Python
increment = lambda x: x + 1
print(increment(4))What changes
Python functions can be passed as callbacks without a Func<T, TResult> declaration. A lambda has one expression; use def for statements. if and for suites do not create local scopes. Assignment anywhere in a function makes that name local unless declared global or nonlocal, which can cause UnboundLocalError when reading it before assignment. nonlocal targets a binding in an enclosing function.
Transfer mistake
Mutating a passed list and rebinding a local name are different operations, much as mutating a C# reference object differs from assigning a by-value parameter. Both languages can capture outer variables; Python loop closures need care because they look up the binding when called.
Your task
Implement transform_all(values, transform). Return a new list obtained by calling the supplied one-argument callback exactly once per original element in encounter order. Leave values unchanged. The driver exercises add-3 and negate callbacks, prints both result lists and call counts, verifies callback argument order, and prints unchanged or changed. Empty input is allowed.
Challenge
BeginnerImplement transform_all(values, transform). Return a new list obtained by calling the supplied one-argument callback exactly once per original element in encounter order. Leave values unchanged. The driver exercises add-3 and negate callbacks, prints both result lists and call counts, verifies callback argument order, and prints unchanged or changed. Empty input is allowed.
Editable implementation files: functions.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.
Keep the supplied imports and exact API names. Return results or raise the required exceptions; do not read input or print from these implementation modules.
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 C# Developers
1C# Foundations in Python
Run the Python WorkspaceOutput, Strings, and CommentsTyped Locals to Python NamesDivision and RemaindersIndentation Instead of BracesRecap: Port a Receipt4Loops and Transformations
From foreach to forIndexes and Dictionary ItemsSentinels and Loop ControlFrom LINQ to ComprehensionsRecap: Stable Ranking2None and Decisions
Nullable Values and NoneEquality, Identity, and TypesTruth Tests and FallbacksBranch PriorityRecap: Eligibility Rules5Functions and Scope
Define Functions and ReturnNamed Arguments and DefaultsStar Arguments and UnpackingCallbacks and Python ScopeRecap: Pricing Functions3Collections and References
From List<T> to listTuples and UnpackingDictionary Keys and ValuesSets, Aliases, and CopiesRecap: Stock Lookup6Reliable Python Programs
Input and Exact OutputExceptions and ValidationImports and the Main GuardType Hints and Runtime TypesRecap: Validate a Batch9Project: Order Processor
Project 1: Order ModelProject 2: Pricing PoliciesPractice on your own: Online Python compiler