Python Keyword Arguments in Function Calls

Introduction

In Python, keyword arguments allow you to pass arguments to a function by specifying the names of the parameters.

This approach matches the values passed to the function and its parameters according to the parameter names rather than the order in which they appear.

This makes function calls more explicit and self-documenting, as you provide the values along with their corresponding parameter names. It also eliminates any ambiguity about the order of arguments and improves code readability.

Benefits of Using Keyword Arguments

Keyword arguments offer several benefits:

  • Readability: By making it clear which values correspond to which parameters, function calls with keyword arguments are more self-explanatory and easy to understand.
  • Flexibility: You can provide arguments in any order and omit some arguments (this requires providing default values in the function definition).

Using Keyword Arguments

Keyword arguments have no special syntax when a function is defined. The parameter names become the keywords that can be used when a function is called.

To start, let’s examine the following function:

def get_greeting(first_name, last_name):
    greeting = f"Hello, {first_name} {last_name}!"
    return greeting

This function returns a greeting string using a person’s full name.

get_greeting("Alice", "Chalmers")

Output:

Hello, Alice Chalmers!

Python knows that “Alice” is the first name and “Chalmers” is the last because of the order the arguments appear in the function call, as given in the function definition.

Changing the order of the arguments will switch the names:

get_greeting("Chalmers", "Alice")

Output:

Hello, Chalmers Alice!

To use a keyword argument in a function call, instead of just putting in the value, start with the parameter name, followed by an equal sign = and then the value.

Example:

get_greeting(first_name="Alice", last_name="Chalmers")

Output:

Hello, Alice Chalmers!

Note that the style convention is that there should be no spaces surrounding the equal sign in the context of keyword arguments.

Because of the keywords, if the order of the arguments is switched, the function still gives the same result:

Example:

get_greeting(last_name="Chalmers", first_name="Alice")

Output:

Hello, Alice Chalmers!

Mixing Positional and Keyword Arguments

In Python, you have the flexibility to mix both positional and keyword arguments when calling a function. This versatility provides the best of both worlds, allowing you to retain the convenience of the concise syntax of positional arguments while also taking advantage of the clarity and readability offered by keyword arguments.

When calling a function, you can provide positional arguments first, followed by keyword arguments. This is a useful approach when some arguments have clear and common values that you want to pass without explicitly specifying their names. The subsequent keyword arguments can be used to provide values for more specific or less common parameters.

To demonstrate, let’s use our previous example function, get_greeting(), but this time add a third, optional parameter, greeting_type, which configures the function with the word it should use for the greeting, originally “Hello”.

def get_greeting(first_name, last_name, greeting_type="Hello"):
    greeting = f"{greeting_type}, {first_name} {last_name}!"
    return greeting

The greeting_type parameter is made optional by providing it the default value of “Hello” in the function definition. If the argument is not supplied, the default is used.

get_greeting("Alice", "Chalmers", greeting_type="Hey")

In the function call above, "Alice" and "Chalmers" are provided as positional arguments for the first_name and last_name parameters, while greeting_type="Hey" is a keyword argument for greeting_type. This allows you to maintain the order for the common first_name and last_name arguments and provide a clear identifier for greeting_type.

Output:

'Hey, Alice Chalmers!'

Common Keyword Argument Pitfalls

Invalid Argument Order

Any keyword argument in a function call must come after all positional arguments are provided, (or equivalently, once a keyword argument is given, all following arguments must be keyword arguments as well.)

Violating the above rule will result in a syntax error.

Example:

get_greeting(greeting_type="Hey", "Alice", "Chalmers")

Output:

...
SyntaxError: positional argument follows keyword argument

Assigning an Argument More Than Once

In the same get_greeting() example, suppose you want to emphasize the first_name argument and pass it with a keyword.

It has to be the last argument because of the above rule. So let’s try the following:

get_greeting("Chalmers", "Hey", first_name="Alice")

Output:

...
TypeError: get_greeting() got multiple values for argument 'first_name'

This didn’t work because the first positional argument is still first_name, despite being passed as a keyword argument later on.

Python considers this as having multiple values for one argument, which it deems invalid.

This error can be daunting because it doesn’t describe the problem very well, but now you know what it means.

The bottom line is that positional arguments are always associated with parameters in the order they appear in the function definition, regardless of any keyword arguments in the call.

If an argument is assigned using its position, it can’t be reassigned again with a keyword.

Skipping Arguments With Default Values

One of the powerful aspects of using keyword arguments in Python functions is the ability to skip providing values for parameters that have default values.

This is useful when you want to use the default behavior of a function for certain parameters while customizing others that come later in the parameter order.

Let’s modify the get_greeting() function from before by adding a fourth parameter, punctuation, which specifies the punctuation at the end of the greeting:

def get_greeting(first_name, last_name, greeting_type="Hello", punctuation="."):
    greeting = f"{greeting_type}, {first_name} {last_name}{punctuation}"
    return greeting

In this function, the parameters greeting_type and punctuation have default values of “Hello” and “.” respectively.

Let’s say that we want to use the default value for greeting_type, but provide custom punctuation.

This is not possible using positional arguments alone because there is no way to omit greeting_type while maintaining the 4th position of punctuation.

Example:

get_greeting("Alice", "Chalmers", "!!!")

Output:

'!!!, Alice Chalmers.'

It didn’t work as desired because the supposed custom punctuation,”!!!”, is in the 3rd position, and therefore assigned to greeting_type.

The solution is to use keyword arguments.

To skip a positional argument, you must pass subsequent arguments using keywords.

Example:

get_greeting("Alice", "Chalmers", punctuation="!!!")

Output:

'Hello, Alice Chalmers!!!'

Now we have it right!

Summary & Reference for Python Keyword Arguments

Keyword arguments in Python provide a powerful way to enhance the readability, flexibility, and clarity of your code when working with functions.


When defining a function, parameter names serve as keywords that can be used when calling the function.

In the following example, first_name and last_name can be used as the argument keywords:

def get_greeting(first_name, last_name):
    greeting = f"Hello, {first_name} {last_name}!"
    return greeting

Calling a function with keyword arguments involves using parameter names followed by an equal sign = and the corresponding values.

get_greeting(first_name="Alice", last_name="Chalmers")  # "Hello, Alice Chalmers!"

Mixing positional and keyword arguments provides the best of both worlds. You can maintain the concise syntax of positional arguments while enhancing clarity with keyword arguments.

def get_greeting(first_name, last_name, greeting_type="Hello"):
    greeting = f"{greeting_type}, {first_name} {last_name}!"
    return greeting

get_greeting("Alice", "Chalmers", greeting_type="Hey")  # "Hey, Alice Chalmers!"

Keyword arguments in a function call must come after all positional arguments are provided.

The following example has a syntax error:

get_greeting(greeting_type="Hey", "Alice", "Chalmers")  
# SyntaxError: positional argument follows keyword argument

If an argument is assigned using its position, it can’t be reassigned again with a keyword.

The following example has a type error:

get_greeting("Chalmers", "Hey", first_name="Alice")  
# TypeError: get_greeting() got multiple values for argument 'first_name'

The error happens because”Chalmers” is assigned to first_name (because it’s the first argument and first_name is the first parameter in the function definition), and then first_name is assigned again with a keyword argument.


Keyword arguments allow skipping of arguments with default values. This is particularly useful when customizing certain parameters while using defaults for others. To skip a positional argument, you must pass subsequent arguments using keywords.

def get_greeting(first_name, last_name, greeting_type="Hello", punctuation="."):
    greeting = f"{greeting_type}, {first_name} {last_name}{punctuation}"
    return greeting

get_greeting("Alice", "Chalmers", punctuation="!!!")  # "Hello, Alice Chalmers!!!"

In the example above, the third argument, greeting_type is skipped, giving it its default value of “Hello” and the fourth argument is customized with a “!!!”.