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
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 PHP Developers
1From PHP to Python
Run Your First Python ProgramEcho, Strings, and printVariables Without Dollar SignsDivision and Numeric TextIndentation and SuitesRecap: Rewrite a Receipt4Iteration and Transformations
Foreach and rangeKeys, Items, and enumerateWhile Without IncrementFilters and Sort KeysRecap: Build a Ranking2Values and Decisions
Null, None, and Missing KeysStrict Equality Is Not isThe Zero String TrapElif and Value SelectionRecap: Eligibility Rules5Functions and Closures
Functions and Mutable InputsNamed Calls and Default StateVariadics and Call UnpackingArrow Capture and Late BindingRecap: Refactor a Pricing Tool3Arrays and Python Collections
PHP Arrays and Python ListsDestructuring and TuplesKeys, Null, and getArray Copies and List AliasesRecap: Clean an Inventory6Input, Errors, and Modules
CLI Input and Exact OutputConversion Errors and CleanupImports Instead of requireType Hints Are Not PHP TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler