Defaults, Keywords, *args, and **kwargs
Scenario: A logger needs a sensible default but also optional extra labels.
New words, in plain English
- Default argument - a parameter value used when none is supplied
- Keyword argument - an argument supplied by parameter name
- *args - extra positional arguments collected in a tuple
- **kwargs - extra named arguments collected in a dict
Required parameters come before defaults. Keyword calls improve clarity. Use variadic arguments when the API truly accepts a flexible number, not to hide an unclear design.
Analogy: A Python program is like a clear set of instructions for a careful helper: names label things, indentation groups steps, and errors explain where the helper became confused.
A small, real example
def log(message, level="INFO", *tags, **fields):
print(level, message, tags, fields)
log("ready", "INFO", "api", host="edge-01")
Tip: Never use a mutable list or dict as a default; use None and create it inside.
Goal: Practice this idea in the py-first-function challenge at/labs/python. Fix the broken program, run it yourself, then usecheckto prove the real end state.