Menu
CoddyTech

Variadics and Call Unpacking

Lesson 24 of 48 in Coddy's Python for PHP Developers course.

PHP uses ... to collect or unpack arguments. Python separates positional packing with *args from keyword packing with **kwargs. Inside a Python function, args is a tuple and kwargs is a dictionary. At a call site, *values expands an iterable into positional arguments and **options supplies string-keyed keyword arguments. PHP 8 variadics can collect named arguments with string keys, while Python exposes them separately.

PHP 8.3

<?php
function total(...$values) { return array_sum($values); }
$values = [2, 3];
echo total(...$values), "\n";

Python

def total(*values, **options):
    return sum(values) * options.get("factor", 1)
values = [2, 3]
print(total(*values, **{"factor": 2}))

Porting trap

The dictionary supplied with ** needs string keys; it is not a general positional spread. Duplicate bindings are errors, so inspect parameter names when combining explicit keywords and unpacked options.

Complete the task in the editable Python files. Keep the required function and class names; the locked driver.py supplies execution.

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 PHP Developers

Practice on your own: Online Python compiler