Aug-04-2020, 07:01 PM
def test(*args, **kvargs): print(type(args), args, type(kvargs), kvargs) test('this', 'is', a='a', test='test') test(*('this', 'is'), **{'a':'a', 'test':'test'})
Output:<class 'tuple'> ('this', 'is') <class 'dict'> {'a': 'a', 'test': 'test'}
<class 'tuple'> ('this', 'is') <class 'dict'> {'a': 'a', 'test': 'test'}
So args is a tuple and kvargs is a dictionary.*(1, 2, 3) extracts the values from the tuple and provides them as separate items instead of a collection. This is called "unpacking". You can also unpack a dictionary though what is returned is less obvious.
You don't have to understand how kvargs works to use it. Even though kvargs is a dictionary you should not be treating it as a dictionary. To extract values from *args and **kvargs you specify arguments for your function:
def leftovers(*args, **kvargs): print(args, kvargs) def filter(a, *args, b='thing', **kvargs): leftovers(*args, **kvargs) filter(1, 2, b=3, c=4)
Output:(2,) {'c': 4}
The function "filter" consumes the first position argument and the 'b' keyword argument. The remaining arguments can be passed on to the "leftovers" function. This is so much simpler than:def leftovers(*args, **kvargs): print(args, kvargs) def filter(*args, **kvargs): a = args[0] b = kvargs['b'] del kvargs['b'] leftovers(args[1:], **kvargs) filter(1, 2, b=3, c=4)