Variadics and Keyword Options
Lesson 24 of 48 in Coddy's Python for Go Developers course.
Go variadic parameters collect values into a slice, and a slice can be expanded with a trailing ... at the call. Python *values collects positional extras into a tuple; **options collects named extras into a dictionary. At a call, * expands an iterable and ** expands a mapping with string keys. A Python function can accept both forms. This is call binding, not an implicit merge policy for duplicated keywords.
Go
Go excerpt: declarations above main, statements inside main. Imports: fmt. The verification bundle contains the complete program.
func total(values ...int) int { result := 0; for _, n := range values { result += n }; return result }
// Inside main:
values := []int{2, 3}
fmt.Println(total(values...))Python
def total(*values, **options):
return sum(values) * options.get("factor", 1)
values = [2, 3]
print(total(*values))
print(total(*values, **{"factor": 4}))Porting trap
Calling f(x=1, **{"x": 2}) raises TypeError because x is bound twice. Python does not silently let the mapping overwrite the explicit keyword.
Challenge
BeginnerImplement scaled_total(*values, **options). Return the sum of integer values times options.get("factor", 1), ignoring other option names. Do not mutate inputs or print. The driver reads integer tokens (possibly none), then a factor, and prints results from an unpacked positional call and a call with unpacked factor options. Go variadic parameters form a slice; Python positional extras form a tuple and keyword extras form a dictionary.
Editable files: functions.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.
Implement the named definitions in the editable modules without input or printing. The driver owns input/output and may call the APIs again on fresh data without producing extra output.
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 Go Developers
1From Go to Python
Run Your First Python ProgramPrinting, Quotes, and CommentsBindings Beyond Go TypesDivision and Growing IntegersIndentation and ScopeRecap: A Python Receipt4Iteration and Transformations
range and Value IterationIndexes and Map EntriesSentinels Without Truth TrapsComprehensions and Stable SortRecap: Stable Ranking2Values, Absence, and Branches
None, nil, and Zero ValuesEquality Is Not IdentityTruth Tests Beyond boolBranches and Value SelectionRecap: Missing or Eligible5Functions and Call Contracts
Functions and Tuple ReturnsDefaults and Named ArgumentsVariadics and Keyword OptionsClosures and Callable ValuesRecap: Pricing Functions3Slices, Maps, and Sharing
Slices Versus Python ListsMultiple Values and TuplesGo Maps and Python dictsSets and Shallow CopiesRecap: Inventory Collections6Errors, Modules, and Hints
Text and Exact OutputErrors Versus ExceptionsPackages and Module ExecutionHints Versus Static TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler