args and kwargs - ek-nath/ek-nath.github.io GitHub Wiki

*args

>>> def concat(*args):
...   print(type(args))
...
>>> concat(1, 2, 4, 5, 6)
<class 'tuple'>
>>> concat(True)
<class 'tuple'>
>>> concat()
<class 'tuple'>

Basically defining a function arg as *args converts whatever arguments you pass to the function into a tuple.

Similarly if a function takes a positional parameters, and at the caller, if you had those arguments in a list, you'd call *args during the call to convert it into an ordered tuple as needed by the function:

In [1]: def concat(a, b, c):
   ...:     print(a, b, c)
   ...:

In [2]: args = [1, 2, 3]

In [3]: concat(args)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-8930ffb993c8> in <module>()
----> 1 concat(args)

TypeError: concat() missing 2 required positional arguments: 'b' and 'c'

In [4]: concat(*args)
1 2 3

**kwargs

Its the same as *args except ** turns it into dictionary instead of a tuple.

In [9]: def concat(**args):
   ...:     for k, v in args.items():
   ...:         print(k, v)
   ...:

In [10]: concat(a=True, b=False)
a True
b False

and

In [15]: def concat(a, b):
    ...:     print (a, b)
    ...:

In [16]: concat(**{'a': True, 'b': False})
True False

In [17]: concat(**{'a': True, 'b': False, 'c': 0})
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-17-98bd4094d1fb> in <module>()
----> 1 concat(**{'a': True, 'b': False, 'c': 0})

TypeError: concat() got an unexpected keyword argument 'c'
⚠️ **GitHub.com Fallback** ⚠️