Dots Versus Star Arguments
Lesson 24 of 48 in Coddy's Python for R Developers course.
R dots collect extra arguments for forwarding or inspection through list. Python separates extra positional arguments into a tuple using a star parameter and extra keyword arguments into a dict using two stars. At a call site, a star expands an iterable and two stars expand a mapping with string keys. R do.call assembles a call from a function and argument list; explicit Python expansion often fills that role. Python has no lazy dots promises: argument expressions are evaluated before the function receives them. Do not treat a plain dict positional argument as if it were expanded keyword arguments.
R
total <- function(..., factor=1) sum(...) * factor
cat(do.call(total, list(2, 3, factor=2)), "\n", sep="")Python
def total(*values, **options):
print(type(values).__name__)
return sum(values) * options.get('factor', 1)
print(total(*[2, 3], **{'factor': 2}))Porting trap
Use explicit expansion to preserve the intended binding. A dictionary passed without two stars is one positional object.
Challenge
BeginnerImplement scaled_total(*values, **options). All values are integers. Return their sum multiplied by options.get("factor", 1). Ignore other option names. Do not mutate collections or print. The driver reads a line of integer tokens (possibly empty) and a factor on the next line. It prints a call with only unpacked values, then a call with unpacked values and a dictionary containing the factor.
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 scaled_total
values = [int(part) for part in input().split()]
factor = int(input())
print(scaled_total(*values))
print(scaled_total(*values, **{"factor": factor, "note": "ignored"}))
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