Keyword Arguments

Python functions offer a great deal of flexibility, and one of their features is the ability to use keyword arguments. A keyword argument is an argument passed to a function, preceded by a keyword that gives the argument context.

Introduction to Keyword Arguments

Keyword arguments, also known as kwargs, are identified by the keyword used when passing them to the function. This is in contrast to positional arguments, which are identified by their order in the argument list.

The primary benefit of keyword arguments is readability. When reading a function call with keyword arguments, it’s clear what each argument is for, since they’re identified by name, not just position. Consider this function call:

1greet(name='John', greeting='Hello')

It’s immediately clear that ‘John’ is the name and ‘Hello’ is the greeting, regardless of the order in which they were passed.

If you pass keyword arguments after positional arguments, Python matches the positional arguments first and then assigns the keyword arguments to the remaining parameters.

Syntax of Keyword Arguments

The syntax for keyword arguments in a function call is to specify the argument name, followed by an equal sign, followed by the argument value. The syntax when defining a function that accepts keyword arguments is the same as for positional arguments:

1def greet(name, greeting):
2    print(f"{greeting}, {name}!")

This function can then be called with keyword arguments:

1greet(name='Jane', greeting='Good morning')

This will print:

Good morning, Jane!

In the function definition, name and greeting are parameters. In the function call, name='Jane' and greeting='Good morning' are keyword arguments.

Rules and Best Practices

Here are few rules and best practices while using keyword arguments:

  • Keyword arguments must follow positional arguments if you’re using both.
  • You can mix positional arguments and keyword arguments in a call to a Python function. Positional arguments must always come before any keyword arguments.
  • Using keyword arguments can make your code more readable, especially if a function has a lot of parameters.
  • It’s a good habit to use keyword arguments for arguments that are optional or have a default value.

Note

When calling a function, you can specify arguments by position, by keyword, or both. Positional arguments need to be passed in the correct order, while keyword arguments can be passed in any order.