What the heck are args and kwargs?
Sun May 19 2019
So you're looking at someone's Python code and see something crazy, like
**kwargs. What the heck are those?
We will have to unpack it since there's a couple things that maybe causing confusion. First off, what does the
** do? Then, what do
kwargs mean? And finally, what is it used for?
* is a way of unpacking the
tuple data structure and the
** is a way of unpacking a
args as you can guess, means arguments. Now
kwargs maybe harder to guess, but you can probably deduce "kw" to mean "keyword". With that, you can guess that
args represents the arguments passed to a function separated by a comma and
kwargs are the keyword arguments.
The main reason for using
kwargs are pretty simple if you're trying to create a higher-order function in Python. Rather than passing in a bunch of named arguments as well as keyword arguments, using
kwargs allows for generalizing the the function signature so that you can accommodate almost any function.