Accepting Any Number of kwargs
For more information on concepts covered in this lesson, you can check out:
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.
00:53
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.
01:13
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.
01:27
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 (**
) operator.
01:49
You can now rewrite add_items()
so that it accepts any number of keyword arguments, as seen on-screen.
02:29
The output from this code displays the items in the dictionary shopping_list
, showing all four things you wish to buy and their respective quantities.
02:37
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.
03:30
To learn more about args
and 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.
03:47 Next, we’ll take a look at what you’ve learned in this course.
Become a Member to join the conversation.