Unpacking Arguments at a Call Site
Argument unpacking supplies elements of a sequence as positional arguments or mapping entries as named arguments where the language permits it.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace a small call
With dimensions = (8, 5), calling area(*dimensions) supplies two positional values. Calling area(dimensions) supplies one tuple. The intended parameters determine which form is legal.
Check for a repeated keyword
Python raises a type error if an explicit width and an unpacked dictionary entry both supply the same named argument. If defaults and overrides come from settings, merge them under a deliberate precedence rule before the call. See keyword arguments for why names are part of a stable interface.[1][2]
Match each value to the signature before running
For box(width, length, *, label) and dimensions = (3, 5), a call with box(*dimensions, **{"label": "A"}) binds width three, length five and label A. Extending the mapping with a width key gives conflicting arguments. Python rejects that call before the function body runs. This matters if the mapping came from user settings. Validate allowed keys and required choices where they enter the system. See keyword arguments.
Know which operations consume the source
Evaluating *source reads all elements before the call. If source is an iterator, a later attempt to iterate it may see nothing. Using an iterable parameter can be simpler when the caller owns a stream and the callee needs only part of it. Test a two-element generator with predictable reads and check what remains after the call. See iterator exhaustion for how to reason about aliases for one cursor.