Varargs Without va_list
Lesson 24 of 48 in Coddy's Python for C Developers course.
C variadic functions use an explicit agreement such as a count or format string to know which promoted argument types to read with va_arg. Python *values collects positional extras into a tuple; **options collects keyword extras into a dictionary. At a call site, * expands an iterable into positional arguments and ** expands a mapping with string keys into keyword arguments. The same punctuation collects in a definition and expands in a call.
C: complete example.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int total(int count, ...) {
va_list ap; va_start(ap, count); int result = 0;
for (int i = 0; i < count; ++i) result += va_arg(ap, int);
va_end(ap); return result;
}
int main(void) {
printf("%d\n", total(3, 2, 4, 6));
return 0;
}Python: complete example.py
def total(*values, **options):
return sum(values) * options.get("factor", 1)
print(total(*[2, 4, 6], **{"factor": 2}))Watch the difference
Python does not require va_start or va_end, but it still rejects duplicate values for a named parameter. These stars are not pointer dereferences. Empty positional extras give an empty tuple whose sum is zero.
Your code goes in functions.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
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.
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.
Python collects positional extras into a tuple instead of requiring C va_list type bookkeeping.
Your code goes in functions.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
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 C Developers
1From C Programs to Python
Run Python Without mainPrinting Without Format CodesNames Versus Typed StorageDivision and Integer LimitsSuites Instead of BracesRecap: A Python Receipt4Iteration and Transformations
Iteration Without PointersIndexes Without Pointer MathSentinels and Loop ControlComprehensions and SortingRecap: Stable Ranking2Values and Truth Tests
Absence Is Not a Null PointerContent Versus Object IdentityTruth Tests and OperandsConditional Value SelectionRecap: Missing or Eligible5Functions and Callbacks
Functions and Object ArgumentsDefaults and Named ArgumentsVarargs Without va_listCallbacks and Captured NamesRecap: Pricing Functions3Containers and Aliasing
Lists Versus C ArraysTuples and Struct ValuesMappings and Lookup LoopsPointers, Copies, and AliasesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputError Codes Versus ExceptionsImports Are Not IncludesAnnotations Versus C TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler