Using Keyword Arguments to Explain a Call

A keyword argument supplies a value to a named parameter, making roles and optional settings more visible at the call site.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Choose clear roles
  2. Plan API changes deliberately
  3. Make similarly typed options distinguishable at the call site
  4. Treat published parameter names as interface commitments

Choose clear roles

A call such as resize(width=120, height=70) communicates the orientation. It also avoids relying on the reader remembering which length is first. See parameters and arguments for how each input reaches the function body.

Plan API changes deliberately

Renaming a public keyword parameter can break callers using the old name while positional calls survive. Test a named call for an interface promised to users. The function contract should treat a supported keyword as part of the interface.[1][2]

Make similarly typed options distinguishable at the call site

Suppose a data preview accepts a positive row limit and a positive byte limit. The call preview(data, 80, 2000) leaves the units implicit. With preview(data, row_limit=80, byte_limit=2000) a reviewer can verify the truncation policies independently. Python can enforce that callers use these names by placing the options after * in the signature. Test a long narrow record list and a single very wide row so swapping the limits changes at least one expected result. See parameters and arguments.

Treat published parameter names as interface commitments

A caller might supply row_limit from a configuration mapping using **settings. Renaming the parameter to max_rows then changes the accepted input even if all numeric results stay the same. A compatibility transition can accept both names, report conflicting values explicitly, and document when the old spelling stops working. Use a distinctive sentinel to distinguish an absent option from zero or a deliberately supplied null if those are valid. See argument unpacking and versioning a function contract.

References

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