Keyword Arguments
Use keyword arguments when a function has many parameters, when the purpose of a value is unclear from its position, or when you want a call to be self-documenting.
Try it: Binding Arguments to Parameters
How Python matches a call's arguments to a function's parameters — positionals left to right, extras into *args, keywords by name, defaults for the rest, unknown names into **kwargs — and the exact SyntaxError or TypeError when a call doesn't fit, including the shared mutable default.
How it works
- The parser checks the call first: a positional after a keyword, or a repeated keyword, is a SyntaxError before anything runs.
- At the call site, *list spreads into separate positional arguments and **dict into keyword arguments.
- Positional arguments fill the parameters left to right; leftovers go into the *args tuple.
- Each keyword matches a parameter by exact name (a second value is 'got multiple values'); unknown names go into **kwargs or raise 'unexpected keyword argument'.
- Then: too many positionals, or a required parameter still empty, is a TypeError; otherwise defaults fill the rest.
- Defaults are evaluated once, at def time: a list default is the same object in every call.
Default run (13 steps): def greet(…) runs once: it creates the function and evaluates its default values right now. Then the call greet('Ann', 'Hi', *[7, 8], sep='-', mood='happy') starts. … Done. Printed: {'name': 'Ann', 'greeting': 'Hi', 'sep': '-', 'args': (7, 8), 'kwargs': {'mood': 'happy'}}.
Simplified: Five hand-written signatures with no positional-only (/) parameters; argument values are small literals (ints, short strs, True/False/None, flat lists). Error messages are CPython 3.12's (3.13+ may add a 'Did you mean' hint).
Loading the simulation…
Why Names Beat Counting
A positional function call depends on order. The first supplied value goes to the first parameter, the second value goes to the second parameter, and so on. This means that calling a function with many parameters requires you to remember the function's exact parameter order. Keyword arguments remove that burden by naming the parameter that should receive each value. The call becomes easier to read because each value is connected directly to its purpose.
Use keyword arguments when a function has many parameters, when the purpose of a value is unclear from its position, or when you want a call to be self-documenting.
Defaults for Optional Parameters
A default argument value makes a parameter optional. In a function definition, write the parameter name, an equals sign, and the value to use when the caller does not provide an argument. The general pattern is parameter_name = default_value. For example, a greeting function might define greeting = "Hello". A caller who supplies no greeting receives the default, while a caller who supplies another greeting receives that supplied value.
Selecting a Greeting
Imagine a function with a message parameter and an optional greeting parameter whose default is "Hello". Determine the value of greeting in two calls: one call omits greeting, and the other supplies "Hi".
- 1Call without greeting
No value is supplied for greeting, so Python uses the default value "Hello".
- 2Call with greeting
The caller supplies "Hi", so Python uses that argument instead of the default.
- 3Parameter state
The function body works with the resulting value in either case. It does not need to treat a supplied value and a default value as different kinds of parameter values.
The first call gives greeting the value "Hello". The second call gives greeting the value "Hi".
Safe Values for Defaults
A default should be a fixed, immutable value. Strings, numbers, tuples, and None are identified as safe default values because they cannot be changed after they are created. Lists and dictionaries are mutable, so they should not be used as defaults. If a mutable default is modified inside the function, that modification can persist across function calls and produce unexpected behavior.
| Default category | Examples | Guidance |
|---|---|---|
| Immutable | Strings, numbers, tuples, None | Safe choices for defaults |
| Mutable | Lists, dictionaries | Avoid as defaults because modifications can persist across calls |
The source identifies immutable values as safe defaults and mutable values as a source of unexpected behavior.
Naming Arguments in Calls
A keyword argument assigns a value by naming the parameter in the function call. The keyword must exactly match a parameter name in the function definition. Python does not guess when the name is misspelled or does not exist; it raises a TypeError. Because matching uses names rather than positions, keyword arguments can appear in any order.
Same Values, Different Order
Consider a function with parameters item, quantity, and discount. Compare a call that names quantity first and discount second with a call that names discount first and quantity second.
- 1First call
The keyword quantity assigns its value to quantity, and discount assigns its value to discount.
- 2Second call
Although the keyword arguments appear in the opposite order, each value is still assigned by its exact parameter name.
- 3Comparison
The order of the keyword arguments does not change the resulting parameter values.
Both calls produce the same parameter mapping because keyword arguments are matched by name rather than position.
Combining Positional and Keyword Forms
A function call may contain both positional and keyword arguments. The required order is strict: every positional argument must appear before every keyword argument. A positional argument after a keyword argument causes a syntax error. This rule keeps the two matching methods unambiguous: Python first handles the values identified by position, then handles the values identified by name.
function(first_value, second_value)
call(first_value=1, 2)A positional argument appears after a keyword argument, so the call is invalid.
function(first_value, second_value)
call(1, second_value=2)The positional argument appears first and the keyword argument appears afterward, so the ordering rule is satisfied.
The safe pattern is positional arguments first, followed by keyword arguments. Once the call has moved to keyword arguments, do not return to positional arguments.
Overriding Selected Defaults
Defaults are useful because they handle the common case without requiring every caller to provide every value. Keyword arguments make customization selective. A caller can name one optional parameter with a special value while omitting other optional parameters, allowing those omitted parameters to keep their defaults.
Changing One Optional Setting
Imagine an order-total function with an optional tax rate whose default is 0.08. Determine what happens when a caller supplies a different tax rate by name but omits the other optional settings.
- 1Start with defaults
The function is designed with a standard tax rate for the common case.
- 2Name the exception
The caller supplies a different value using the tax-rate parameter name.
- 3Keep omitted defaults
Any other optional parameter that the caller does not name continues to receive its own default value.
The named tax-rate parameter uses the caller's value, while other omitted optional parameters use their defaults.
Mistakes in Argument Matching
Common mistake Relying on position when the purpose of each value is unclear
What it looks likeA call supplies several values in sequence without identifying which parameter each value is meant to configure.
Why it failsThe caller must remember the exact parameter order, and a misplaced value can be assigned to the wrong parameter.
Do this insteadUse keyword arguments so each value is connected to its parameter name.
Common mistake Putting a positional argument after a keyword argument
What it looks likeA call names one parameter and then supplies an unnamed value.
Why it failsPython requires all positional arguments to come before all keyword arguments, so the call raises a syntax error.
Do this insteadMove the positional value before the keyword arguments, or name it as a keyword argument.
Common mistake Misspelling a keyword argument
What it looks likeA caller uses a name that resembles a parameter name but does not exactly match it.
Why it failsPython does not guess or match similar names; an unknown keyword produces a
TypeError.Do this insteadUse the exact parameter name from the function definition.
Common mistake Using a mutable value as a default
What it looks likeA list or dictionary is selected as a default and then modified inside the function.
Why it failsThe modification can persist across function calls and lead to unexpected behavior.
Do this insteadUse an immutable default such as a string, number, tuple, or None.
Check Your Understanding
A function is designed with three parameters: item, quantity, and discount. Quantity and discount have default values. Describe how you would call the function when you want to provide item and a custom discount but allow quantity to keep its default. Then describe why the positional part of the call must come before the keyword part.
Hints
- Supply the required item value first if it is being passed positionally.
- Name the discount parameter explicitly.
- Do not place an unnamed positional value after the named discount argument.
- The omitted quantity parameter receives its default.
What do you think happens?
A function has an optional greeting parameter with the default value "Hello". A caller supplies greeting="Greetings". Which value does greeting hold inside that call?
Reveal answer
"Greetings"
A supplied argument takes precedence over the default. The default is used only when the parameter is omitted.
What to Remember
- 1Positional arguments are matched by order; keyword arguments are matched by exact parameter name.
- 2Write
parameter_name=default_valuein a function definition to make a parameter optional. - 3A supplied argument replaces its parameter's default, while an omitted optional parameter keeps its default.
- 4Use immutable defaults such as strings, numbers, tuples, or None; avoid mutable defaults such as lists and dictionaries.
- 5When combining argument styles, place every positional argument before every keyword argument.
At a glance
- Keyword arguments name the parameters receiving values, so their order does not matter.
- Default values provide fallback values for omitted optional parameters.
- Each parameter independently receives either its supplied argument or its default.
- Keyword names must exactly match parameter names.
- Positional arguments must come before keyword arguments in a combined call.