Variadics and Call Expansion
Lesson 24 of 48 in Coddy's Python for Swift Developers course.
Swift variadic parameters collect values in an array, but you do not generally spread an existing array into a variadic call with Python syntax. Python *args collects extra positional arguments into a tuple, and **kwargs collects keyword arguments into a dictionary. At a call, *sequence expands positional values and **mapping expands string-keyed keyword arguments. These are call operations, not Swift inout or pointer operators. Duplicate bindings raise an error.
Swift example
func total(_ values: Int..., factor: Int) -> Int {
values.reduce(0, +) * factor
}
print(total(2, 3, factor: 2))Python
def total(*values, **options):
return sum(values) * options.get("factor", 1)
print(total(*[2, 3], **{"factor": 2}))Porting trap
Unpacking is one level only. Nested collections remain nested unless you explicitly flatten them.
Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.
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 Swift Developers
1From Swift to Python
Run Your First Python ProgramPrinting and Stringslet, var, and RebindingInt Range and DivisionIndentation and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for and Half-Open Rangesenumerated to enumeratewhile and Loop Controlmap, filter, ComprehensionsRecap: Build a Ranking2Values and Decisions
Optionals and NoneEquatable and IdentityBool Conditions and FallbacksBranches and TernariesRecap: Eligibility Rules5Functions and Closures
Functions and Explicit ReturnArgument Labels and DefaultsVariadics and Call ExpansionCapture Lists and DefaultsRecap: Refactor a Pricing Tool3Value Types to Shared Objects
Array to listTuples and UnpackingDictionary Lookup and OrderValue Copies and AliasesRecap: Clean an Inventory6Errors and Modules
Input and String Formattingthrows, defer, and withModules and Main GuardsHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler