kwargs (keyword arguments)
In Python, **kwargs is a special syntax for defining functions that accept an undetermined number of keyword arguments.
The kwargs parameter captures any extra keyword arguments into a dictionary, where the keys are the argument names and the values are the actual arguments. This behavior allows your function to handle any number of keyword arguments.
Using **kwargs can be particularly beneficial in scenarios where you want to take an unknown number of arguments or when you want to accept optional arguments.
Example
Here’s a quick example demonstrating how to use **kwargs in a Python function:
>>> def concatenate(**kwargs):
... return " ".join(kwargs.values())
...
>>> concatenate(a="Welcome", b="to", c="Real", d="Python!")
'Welcome to Real Python!'
In this example, the concatenate() function can take any number of keyword arguments. The function packs all the keyword arguments in a dictionary. Next, you use the str.join() method to concatenate the arguments and generate a final string.
Note that this example relies on **kwargs preserving the order in which you pass the keyword arguments, which is guaranteed since Python 3.6 (PEP 468).
Related Resources
Tutorial
Python args and kwargs: Demystified
In this step-by-step tutorial, you'll learn how to use args and kwargs in Python to add more flexibility to your functions. You'll also take a closer look at the single and double-asterisk unpacking operators, which you can use to unpack any iterable object in Python.
For additional information on related topics, take a look at the following resources:
- Python args and kwargs: Demystified (Course)
- Using Python Optional Arguments When Defining Functions (Tutorial)
- Defining Python Functions With Optional Arguments (Course)
- Dictionaries in Python (Tutorial)
- Python args and kwargs: Demystified (Quiz)
- Using Python Optional Arguments When Defining Functions (Quiz)
- Using Dictionaries in Python (Course)
- Dictionaries in Python (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.