Returning Several Related Values

A function can return one structured result containing several related values so callers receive a coherent observation.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Share the same calculation
  2. Make the field order discoverable
  3. Use a small example that checks every component
  4. Choose a result shape that survives more callers

Share the same calculation

For a division of seventeen items into groups of five, a Python function can return a pair (3, 2). The quotient and remainder describe the same split. Returning them together avoids reevaluating mutable input in two separate calls.

Make the field order discoverable

Positions in a pair are useful when there are two familiar results. If the result has several counts with the same type, a record with named fields clarifies which one is total or missing. Unpacking helps with short, stable pairs.[1][2]

Use a small example that checks every component

A scan that locates a minimum and its index could return (2, 1) for [5, 2, 2, 7] when ties select the first position. Interchanging those components silently returns a valid-looking pair of integers. Use a case where they differ, and document whether the position is zero-based. When the scan accepts an empty input, either define a separate result shape or give the exception a clear domain meaning. See zero-based indexing and finding both extremes.

Choose a result shape that survives more callers

A pair is natural when two parts are always used together, as in divmod(19, 4) returning quotient four and remainder three. If a scan later needs tie count, input extent or units, every fixed-size unpacking assignment would need a change. An immutable result with named fields can let readers select only what they need. Test the published field values directly to detect accidental swaps. Decision results with a reason illustrate another use of an explicit result record.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩
  2. Python Software Foundation, Python Language Reference: Execution Model ↩