What the heck are args and kwargs?

Sun May 19 2019

Photo by Matt Artz on Unsplash

So you're looking at someone's Python code and see something crazy, like *args and **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 * and ** do? Then, what do args and kwargs mean? And finally, what is it used for?

The * is a way of unpacking the list or tuple data structure and the ** is a way of unpacking a dict. 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 args and 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 args and kwargs allows for generalizing the the function signature so that you can accommodate almost any function.

Reference

Unpacking Argument Lists

If you found the post helpful and would like this same content delivered to you,

Subscribe to my newsletter

;