Functions Accepting a Variable Number of Arguments
A variadic signature can collect zero or more supplied positional values. Give the empty case a documented meaning.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Read the collected values
In Python, a definition using *scores binds the collected scores as a tuple. A call with 4 and 7 supplies a tuple of length two. That signature differs from one accepting a single list. Read parameter binding to distinguish the two calls.
Check the mathematical neutral element
A sum over no values can return zero. A maximum needs a missing result or an explicit error. Test the empty case and a two-value case so a caller can rely on the function contract rather than infer it from incidental implementation details.[1][2]
Trace the collected values and the identity case
In Python, def total(*amounts) binds a tuple containing all extra positional values. A call total(8, 1, -2) can sum the tuple to seven. The call total() supplies the empty tuple, so accepting it can naturally mean returning zero. A mean has no similar identity because dividing by the length would divide by zero. Decide whether at least one value is required and test absence. See loop accumulators for reasoning about identity values.
Specify how an iterable enters the interface
The argument in total([8, 1, -2]) is a single list, so the collected tuple has length one. Use total(*sequence) only when expansion matches the interface. If the input can be very large or infinite, a function taking an iterable directly can consume values progressively, whereas argument unpacking must collect them before entry. Test both a fixed list and a generator. See unpacking at a call site.