Environments and nonlocal
Lesson 25 of 48 in Coddy's Python for R Developers course.
R closures retain an enclosing environment; Python nested functions retain access to enclosing bindings. R double-arrow assignment searches parent environments for a binding and may reach the global environment. Python nonlocal explicitly selects a binding in an enclosing function scope, while global selects module scope. These are not interchangeable lookup rules. Python lambda has one expression and returns its value; a def body can contain multiple statements. Pass a function itself when a callback is required rather than invoking it prematurely. State retained in a closure lasts across calls, which is useful for counters and accumulators.
R
counter <- function() {
n <- 0
function() { n <<- n + 1; n }
}
f <- counter()
cat(f(), "\n", sep="")
cat(f(), "\n", sep="")Python
def counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
increment = counter()
print(increment())
print(increment())Porting trap
Python assignment in a nested function creates a local unless declared otherwise. Reading an outer name and then assigning it without nonlocal can fail.
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 R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules5Functions and Environments
Explicit Function ReturnsLazy and Eager DefaultsDots Versus Star ArgumentsEnvironments and nonlocalRecap: Refactor a Pricing Tool3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler