Concepts / Keyword Arguments

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.

  • Programming
Interactive lab

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

  1. The parser checks the call first: a positional after a keyword, or a repeated keyword, is a SyntaxError before anything runs.
  2. At the call site, *list spreads into separate positional arguments and **dict into keyword arguments.
  3. Positional arguments fill the parameters left to right; leftovers go into the *args tuple.
  4. 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'.
  5. Then: too many positionals, or a required parameter still empty, is a TypeError; otherwise defaults fill the rest.
  6. 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).

Educational simulation

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.

Positional callfirst, second, thirdmessagefirst valuemessagenamed valuegreetingsecond valueKeyword callparameter namesgreetingnamed valueposition 1position 2message=greeting=
How does each supplied argument get matched to a parameter when arguments are passed by position versus by name?
Key point

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.

Worked example

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".

  1. 1
    Call without greeting

    No value is supplied for greeting, so Python uses the default value "Hello".

  2. 2
    Call with greeting

    The caller supplies "Hi", so Python uses that argument instead of the default.

  3. 3
    Parameter 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.

Result

The first call gives greeting the value "Hello". The second call gives greeting the value "Hi".

Function callArgument suppliedProvided argumentParameter valueDefault valueinspect parameteryesnobindbind
What value does each parameter hold when a function is called with some arguments omitted?

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 categoryExamplesGuidance
ImmutableStrings, numbers, tuples, NoneSafe choices for defaults
MutableLists, dictionariesAvoid 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.

Worked example

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.

  1. 1
    First call

    The keyword quantity assigns its value to quantity, and discount assigns its value to discount.

  2. 2
    Second call

    Although the keyword arguments appear in the opposite order, each value is still assigned by its exact parameter name.

  3. 3
    Comparison

    The order of the keyword arguments does not change the resulting parameter values.

Result

Both calls produce the same parameter mapping because keyword arguments are matched by name rather than position.

Call Aquantitynamed valuediscountnamed valueSame parameter valuesdiscountnamed valueCall Bquantitynamed valuefirst keywordsecond keywordfirst keywordsecond keywordname matchname match
How do two calls with the same named arguments produce the same parameter values even when the arguments appear in different orders?

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 callPositional argumentsValid callKeyword argumentsSyntax erroroptional firstthenno later positional valuepositional value follows
In what order can positional and keyword arguments appear, and when does a function call become invalid?
Before
function(first_value, second_value)
call(first_value=1, 2)

A positional argument appears after a keyword argument, so the call is invalid.

After
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.

Key point

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.

Worked example

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.

  1. 1
    Start with defaults

    The function is designed with a standard tax rate for the common case.

  2. 2
    Name the exception

    The caller supplies a different value using the tax-rate parameter name.

  3. 3
    Keep omitted defaults

    Any other optional parameter that the caller does not name continues to receive its own default value.

Result

The named tax-rate parameter uses the caller's value, while other omitted optional parameters use their defaults.

tax rate0.08tax ratecaller valueother optiondefaultother optiondefaultkeyword overrideomitted argument
How can a caller change only one optional parameter while allowing the other parameters to keep their default values?

Mistakes in Argument Matching

  • Common mistake

    Relying on position when the purpose of each value is unclear

    What it looks like

    A call supplies several values in sequence without identifying which parameter each value is meant to configure.

    Why it fails

    The caller must remember the exact parameter order, and a misplaced value can be assigned to the wrong parameter.

    Do this instead

    Use keyword arguments so each value is connected to its parameter name.

  • Common mistake

    Putting a positional argument after a keyword argument

    What it looks like

    A call names one parameter and then supplies an unnamed value.

    Why it fails

    Python requires all positional arguments to come before all keyword arguments, so the call raises a syntax error.

    Do this instead

    Move the positional value before the keyword arguments, or name it as a keyword argument.

  • Common mistake

    Misspelling a keyword argument

    What it looks like

    A caller uses a name that resembles a parameter name but does not exactly match it.

    Why it fails

    Python does not guess or match similar names; an unknown keyword produces a TypeError.

    Do this instead

    Use the exact parameter name from the function definition.

  • Common mistake

    Using a mutable value as a default

    What it looks like

    A list or dictionary is selected as a default and then modified inside the function.

    Why it fails

    The modification can persist across function calls and lead to unexpected behavior.

    Do this instead

    Use an immutable default such as a string, number, tuple, or None.

Check Your Understanding

MEDIUM

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?

  • "Hello"

  • "Greetings"

  • No value

Reveal answer
Answer:

"Greetings"

A supplied argument takes precedence over the default. The default is used only when the parameter is omitted.

What to Remember

  1. 1
    Positional arguments are matched by order; keyword arguments are matched by exact parameter name.
  2. 2
    Write parameter_name = default_value in a function definition to make a parameter optional.
  3. 3
    A supplied argument replaces its parameter's default, while an omitted optional parameter keeps its default.
  4. 4
    Use immutable defaults such as strings, numbers, tuples, or None; avoid mutable defaults such as lists and dictionaries.
  5. 5
    When 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.

Related concepts

More concepts starting with K