What the heck are args and kwargs?

May 19, 2019

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

Subscribe

I'd like to send you a weekly recap of all the articles I write as well as my take on the latest news on web development with Vue, React, Elixir/Phoenix, and others. Just fill out your email and name below!


Prev: Associate HTML as Jinja Files in VSCode
Next: Setting Up TypeScript for Node