Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a star * alone mean in a function declaration? [duplicate]

What does the * mean in the following code (found in the pprint library)?

def pformat(object, indent=1, width=80, depth=None, *, compact=False):
    """Format a Python object into a pretty-printed representation."""
    return PrettyPrinter(indent=indent, width=width, depth=depth,
                         compact=compact).pformat(object)

If it was *args then it would be an arbitrary number of positional parameters. The parameter values would be in the tuple called args. The first 4 parameters could be assigned either by name or by position, the parameter compact could only be assigned by name...

Well, NO! Because it doesn't agree with the documentation:

In a function call, keyword arguments must follow positional arguments.

So, what does the star do after and before other named arguments? And how is that used? Or why is it there if it is not used?

like image 237
stenci Avatar asked Sep 22 '15 21:09

stenci


People also ask

What is the use of single * In Python function?

Python3. Here a single asterisk( * ) is also used in *args. It is used to pass a variable number of arguments to a function, it is mostly used to pass a non-key argument and variable-length argument list.

What is * Kwargs in Python?

**kwargs allows us to pass a variable number of keyword arguments to a Python function. In the function, we use the double-asterisk ( ** ) before the parameter name to denote this type of argument.


1 Answers

It separates positional arguments from keyword-only arguments when there are no variable arguments. This is a Python-3-only feature.

like image 66
BrenBarn Avatar answered Oct 02 '22 14:10

BrenBarn