Menu
CoddyTech

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 icon

Challenge

Beginner

Implement 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"}))
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