Varargs and Call Unpacking
Lesson 24 of 48 in Coddy's Python for Luau Developers course.
Luau ... carries variadic values, and table.unpack can expand a sequence at the final argument position. Python *values collects extra positional arguments into a tuple and **options collects keywords into a dictionary. At a call, * expands an iterable and ** expands string-keyed keywords. Python does not use Luau’s multiple-result adjustment rules; duplicate names or incompatible bindings raise errors.
Luau example
local function total(factor, ...)
local result = 0
for _, n in ipairs({...}) do result = result + n end
return result * factor
end
print(total(2, table.unpack({2, 3})))Python
def total(*values, **options):
return sum(values) * options.get("factor", 1)
print(total(*[2, 3], **{"factor": 2}))Porting trap
Unpacking expands one level, not nested lists recursively. Use explicit flattening logic for nested data.
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 Luau Developers
1From Luau to Python
Run Your First Python ProgramPrinting and TextNames and Local ScopeNumbers and ConversionSuites Instead of endRecap: Rewrite a Receipt4Iteration and Transformations
Numeric for to rangepairs, ipairs, and itemsLoop Control and SkipsComprehensions and SortingRecap: Build a Ranking2Values and Decisions
nil Versus NoneTable Identity and EqualityTruthiness Is Differentelif and Value SelectionRecap: Eligibility Rules5Functions and Closures
Returns and Shared ParametersDefaults and Named CallsVarargs and Call UnpackingUpvalues and Late BindingRecap: Refactor a Pricing Tool3Tables to Typed Collections
Sequence Tables to ListsTuples and Multiple ReturnsRecords to DictionariesSets and Shared TablesRecap: Clean an Inventory6Errors and Modules
Input and Exact Textpcall to Exceptionsrequire to importHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler