Packing Calls and Options
Lesson 24 of 48 in Coddy's Python for Rust Developers course.
Rust commonly accepts a slice for a variable-length homogeneous input, and an options struct for named settings. Python *values collects extra positional arguments into a tuple; **options collects extra keyword arguments into a dictionary. At a call, *sequence expands positional values and **mapping supplies keyword values with string keys. These operators do not mean Rust dereferencing. Duplicate keyword bindings fail rather than silently overriding one another.
Rust excerpt inside main
fn total(values: &[i32], factor: i32) -> i32 {
values.iter().sum::<i32>() * factor
}
println!("{}", total(&[2, 3], 2));Python
def total(*values, **options):
return sum(values) * options.get("factor", 1)
print(total(*[2, 3], **{"factor": 2}))Porting trap
Call unpacking expands one level. It does not recursively flatten nested collections, and accepting arbitrary keywords does not validate their names automatically.
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 Rust Developers
1From Rust to Python
Run Your First Python ProgramMacros to printBindings, mut, and ShadowingIntegers and Floor DivisionIndentation and ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Borrowed Iteration to forEntries and enumeratewhile, break, and continueIterators and ComprehensionsRecap: Build a Ranking2Values and Decisions
Option and NoneEquality and Object IdentityTruth Tests and FallbacksIf Expressions and elifRecap: Eligibility Rules5Functions and Closures
Functions and Shared ObjectsNamed Arguments and DefaultsPacking Calls and OptionsClosures and Capture TimingRecap: Refactor a Pricing Tool3Ownership and Collections
Vec to listTuples and DestructuringHashMap to dictClone and Shallow CopiesRecap: Clean an Inventory6Errors and Modules
Text Input and FormattingResult, Exceptions, and withModules and the Main GuardHints Without Borrow CheckingRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler