Dada
|> Structures
|> Algorithms

Python's args and kwargs

how to collect a variable number of arguments

tldr

The *args and **kwargs parameter pattern is a way to collect an unknown number of function arguments. The names "args" and "kwargs" is a convention; the important part is the single or double star. A single star will return the arguments as a list. The double start will return the argument as a dictionary.

The long story

Sometimes you need to give your function a variable number of arguments. You don't know in advance how many you are going to need. Let's say that you want to create a function that gives you the sum of some numbers. You don't know how many number there will be. That is when you use *args

  >>> def sum(*args):
  ...   result = 0
  ...   for n in args:
  ...    result += n 
  ...   return result
  ...
  >>> sum(10)
  10
  >>> sum(10,20,30)
  60

Wouldn't it be nice if there was something similar for dictionaries? There is! That is what **kwargs is for. Let's write a function that updates a dictionary with new values.

  >>> data = { "apple": 1, "ball": 2, "cat": 3 }
  >>> def update(db, **kwargs):
  ...   for key, value in kwargs.items():
  ...     db[key] = value
  ...
  >>> update(data, apple=2, deer=4)
  >>> print(data)
  {'apple': 2, 'ball': 2, 'cat': 3, 'deer': 4}

For more details, read the article on args and kwargs [1], which is the basis of this entry. References:

[1] M. Y. U. Khalid, Python Tips, https://book.pythontips.com/en/latest/args_and_kwargs.html, (accessed 5 August, 2020).