Lazy and Eager Defaults
Lesson 23 of 48 in Coddy's Python for R Developers course.
R arguments use promises, and defaults are evaluated when needed in the function's environment. Python arguments are evaluated before a call, and default expressions are evaluated when def executes. A mutable Python default therefore persists across calls. Use None and allocate inside the function for fresh per-call state. R also allows partial argument matching in some calls, while Python ordinary keyword names must match exactly. Both languages support positional and named calls, but those matching and evaluation rules differ. Avoid relying on R's deferred evaluation or argument abbreviations when designing a Python API.
R
n <- 1
f <- function(x=n) x
n <- 2
cat(f(), "\n", sep="")Python
def collect(items=[]):
items.append(1)
return len(items)
print(collect())
print(collect())Porting trap
An R default depending on a changing outer value may observe it later; a Python default captures its evaluated object when the function is defined.
Challenge
BeginnerImplement line_cost(price, quantity=1, discount=0). Return price * quantity - discount as an integer. Inputs are nonnegative integers and the discount never exceeds the product. Do not print or read input. The locked driver reads price, quantity, and discount on three lines. It calls your function with just price, with two positional arguments, and with all arguments named in a different order. It prints the three results on separate lines.
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 line_cost
price = int(input())
quantity = int(input())
discount = int(input())
print(line_cost(price))
print(line_cost(price, quantity))
print(line_cost(discount=discount, price=price, quantity=quantity))
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