Blocks Become Callables
Lesson 25 of 48 in Coddy's Python for Ruby Developers course.
Ruby blocks, procs, and lambdas supply behavior to iteration methods. Python functions are ordinary callable objects and can be passed directly as arguments. A Python lambda is restricted to a single expression whose value is returned; use def for multiple statements. Ruby closures can update an existing outer local. Python assignment in a nested function normally makes that name local, so use nonlocal to rebind a name in an enclosing function. Merely reading an outer binding needs no declaration. Python closures also look up captured names when called, so loop-generated callbacks can all observe the final loop value.
Ruby
count = 0
increment = -> { count += 1 }
puts increment.call
puts countPython
def counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
increment = counter()
print(increment())
print(increment())Porting trap
Passing a function object is different from calling it immediately. Supply the callable itself to the task's transform parameter.
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 Ruby Developers
1From Ruby to Python
Run Your First Python ProgramStrings and InterpolationNames and Mutable StringsDivision and ParsingFrom end to IndentationRecap: Rewrite a Receipt4Iteration and Transformations
each and Python foreach_pair and enumeratenext Becomes continueselect, map, and sort_byRecap: Build a Ranking2Values and Decisions
nil Becomes None== and equal?Zero Is False in Pythonelsif and Conditional ValuesRecap: Eligibility Rules5Functions and Closures
Explicit Return ValuesDefaults Run at DefinitionSplat and Double SplatBlocks Become CallablesRecap: Refactor a Pricing Tool3Collections and References
Array Methods and ListsParallel Assignment and TuplesHash Defaults and Dict Keysdup, Copies, and SetsRecap: Clean an Inventory6Reliable Python Programs
gets, input, and Formattingrescue and Context Managersrequire and Import GuardsHints Do Not Enforce TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler