Menu
CoddyTech

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 icon

Challenge

Beginner

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

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

All lessons in Python for R Developers

Practice on your own: Online Python compiler