Python: Function Rest Keyword Parameters (**name)

By Xah Lee. Date: .

Unspecified number of unnamed keyword parameters (Double asterisk **)

For unspecified number of unnamed keyword parameters. You need to put a **name as last item in your parameter list in definition. 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'>

Keyword rest parameters must be the last

The **name 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}