Menu
CoddyTech

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 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 C++ Developers

Practice on your own: Online Python compiler