Python – *args, **kwargs and the normal ones (arg)

The good, the bad and the ugly is a famous western. In Python, “the ugly” is probably the **kwargs, as far as it has two stars before it. Anyhow, the idea of *args, **kwargs and arg is simply to pass arguments.

  • Arg (or the normal ones) are the standard arguments in python. You declare one, you pass one, you get one.
  • *Args are a bit fancier – you declare just 1 in the function with one star on the left and you pass as many as you want. From 1 to unlimited.
  • **Kwargs are for named arguments. You may pass as many as you want as well.

Kwargs example

The code below takes 3 named arguments and returns both the keys and the values. On a new line, due to the “magic” of the list comprehension:

Args example

The args are unlimited. And as this is python, these could be of any type. What if we have nothing better to do, but to pass both numbers and strings as args* to a function, which has the task to split those into strings and numbers. The numbers are to be summed together and the strings are to be united? Well, here is how it looks like:

Arg, *Args and **Kwargs together

I really wish to think that the above will never exist in production code. Ever. However, just for learning purposes, this is how to put all 3 types in a single function:

Enjoy it! 🙂

Tagged with: , , , , , ,