Packing and Unpacking Calls
Lesson 24 of 48 in Coddy's Python for C++ Developers course.
Python *values collects extra positional arguments into a tuple; **options collects extra keyword arguments into a dict. At a call site, *sequence and **mapping expand arguments. This is runtime argument binding, unlike C++ template parameter packs instantiated at compile time. A C++ initializer_list can collect homogeneous values but does not supply Python keyword semantics. Dictionary keys used for ** expansion must be strings naming keyword arguments.
C++17 excerpt: inside main
Standard-library headers are supplied in the runnable companion program.
auto total = [](std::initializer_list<int> values, int factor) {
return std::accumulate(values.begin(), values.end(), 0) * factor;
};
std::cout << total({2, 3}, 2) << '\n';Python
def total(*values, **options):
return sum(values) * options.get("factor", 1)
print(total(*[2, 3], **{"factor": 2}))Porting trap
Expanding two mappings that supply the same keyword raises TypeError. Python does not resolve duplicated call arguments by keeping the last one.
Implement the task below in its editable Python modules. The locked driver.py supplies execution and checks. Keep the specified imports and API names.
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 C++ Developers
1From C++ to Python
Run Your First Python ProgramStreams to printNames, auto, and constDivision and Integer RangeBlocks and Name ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Range Loops and RebindingEntries and enumerateLoop Control Without ++Algorithms and ComprehensionsRecap: Build a Ranking2Values and Decisions
None, nullptr, and boolValues, Addresses, IdentityTruth Tests and OperandsBranches and Value SelectionRecap: Eligibility Rules5Functions, Calls, and Closures
Functions and Shared ObjectsDefaults and Named ArgumentsPacking and Unpacking CallsClosures and Capture TimingRecap: Refactor a Pricing Tool3STL Habits and Python Objects
From vector to listTuples and Structured BindingsMaps, Keys, and OrderingValue Copies and Shared ListsRecap: Clean an Inventory6Errors, Resources, and Modules
Text Input and Exact OutputExceptions and RAIIModules Instead of HeadersHints Are Not Static TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler