Bare asterisk in function arguments? Bare asterisk in function arguments? python python

Bare asterisk in function arguments?

Bare * is used to force the caller to use named arguments - so you cannot define a function with * as an argument when you have no following keyword arguments.

See this answer or Python 3 documentation for more details.

While the original answer answers the question completely, just adding a bit of related information. The behaviour for the single asterisk derives from PEP-3102. Quoting the related section:

The second syntactical change is to allow the argument name tobe omitted for a varargs argument. The meaning of this is toallow for keyword-only arguments for functions that would nototherwise take a varargs argument:    def compare(a, b, *, key=None):        ...

In simple english, it means that to pass the value for key, you will need to explicitly pass it as key="value".

def func(*, a, b):    print(a)    print(b)func("gg") # TypeError: func() takes 0 positional arguments but 1 was givenfunc(a="gg") # TypeError: func() missing 1 required keyword-only argument: 'b'func(a="aa", b="bb", c="cc") # TypeError: func() got an unexpected keyword argument 'c'func(a="aa", b="bb", "cc") # SyntaxError: positional argument follows keyword argumentfunc(a="aa", b="bb") # aa, bb

the above example with **kwargs

def func(*, a, b, **kwargs):    print(a)    print(b)    print(kwargs)func(a="aa",b="bb", c="cc") # aa, bb, {'c': 'cc'}