Python: Function var-keyword parameter (**x)
Unspecified number of unnamed keyword parameters
In function definition, you can add **x as last item in your parameter list.
The function receive it as a Dictionary.
# unspecified number of keyword args def ff(**dd): return dd rr = ff( z = 8, c = 7, aa = 4, b = 3) print(rr) # {'z': 8, 'c': 7, 'aa': 4, 'b': 3} print(type(rr)) # <class 'dict'>
this is especially useful if want to pass a dictionary as keyword arguments in function call.
# unspecified number of keyword args def ff(**dd): return dd xdict = {"z": 8, "c": 7, "aa": 4, "b": 3} # unpact the dict as keyword arguments rr = ff(**xdict) print(rr) # {'z': 8, 'c': 7, 'aa': 4, 'b': 3} print(type(rr)) # <class 'dict'>
if a parameter already has a name matching a key in the passed dict, it eats that value:
def ff(b, **dd): return [b, dd] xdict = {"z": 8, "c": 7, "aa": 4, "b": 3} # unpact the dict as keyword arguments rr = ff(**xdict) print(rr) # [3, {'z': 8, 'c': 7, 'aa': 4}] # note, in the received dict, the key b is gone.
you can force the **dict parameter to not interact with previous parameters, by using the /.
it forces parameters before it to accept positional arguments only.
se
Python: Positional Only Parameters (/)
def ff(b, /, **dd): return [b, dd] xdict = {"z": 8, "c": 7, "aa": 4, "b": 3} # unpact the dict as keyword arguments rr = ff(3, **xdict) print(rr) # [3, {'z': 8, 'c': 7, 'aa': 4, 'b': 3}] # note, in the received dict, the key b is gone.
Keyword rest parameters must be the last
The **x can be used with positional paramaters. But it must be the last.
def ff(a, b=1, c=1, **xyz): # xyz is a dictionary print("a is: ", a) print("b is: ", b) print("c is: ", c) print("xyz is: ", xyz) # note, no b ff(3, rabbit = 7, cat = "a", tiger = 33, c = 8) # a is: 3 # b is: 1 # c is: 8 # xyz is: {'rabbit': 7, 'cat': 'a', 'tiger': 33}
Rest parameters and keyword rest parameters
The positional parameters, and *tup tuple and **dict dictionary can be used together, but tuple must come first.
def ff(aa, *bb, **cc): # bb is a tuple # cc is a dictionary print("aa is:", aa) print("bb is:", bb) print("cc is:", cc) ff(3, 4, 5, 6, rabbit=7, cat=9, tiger=33) # aa is: 3 # bb is: (4, 5, 6) # cc is: {'rabbit': 7, 'cat': 9, 'tiger': 33}