For more information on concepts covered in this lesson, you can check out:
Accepting Any Number of kwargs
00:00 Functions Accepting Any Number of Keyword Arguments. When you define a function with parameters, you have a choice of calling the function using either non-keyword arguments or keyword arguments.
00:21 In this first function call, the arguments are passed by position. In this function call, they’re passed by keyword. If you use keyword arguments, you no longer need to input arguments in the order they’re defined.
You can change this default behavior by declaring positional-only arguments or keyword-only arguments, as seen in this Real Python tutorial. When defining a function, you can include any number of optional keyword arguments to be included using
kwargs, which stands for keyword arguments.
The function signature is seen on-screen. The parameter name
kwargs is preceeded by two asterisks. The double asterisk (
**) operates similarly to the single one you used earlier to unpack items from a sequence.
The double asterisk is used to unpack items from a mapping. A mapping is a data type that has paired values as items, such as a dictionary. The parameter name
kwargs is often used in function definitions, but once again, the parameter can have any other name as long as it’s preceded by the double asterisk (
You included this information as keyword arguments when you called the function. Earlier, you learned that
args is a tuple, and the optional non-keyword arguments used in function call are stored as items in that tuple.
02:56 The optional keyword arguments are stored in a dictionary, and the keyword arguments are stored as key-value pairs in this dictionary. This concept can be explored in the REPL using the abbreviated example seen on-screen.
To learn more about
kwargs, check out this Real Python tutorial. You’ll also find more about keyword and non-keyword arguments in functions and the order in which arguments can be used in this Real Python tutorial.
Become a Member to join the conversation.