Star (*) as a parameter in python function

Question:

I was looking at the definition of the glob function and I noticed that the second parameter was simply *.

def glob(pathname, *, recursive=False):
    """Return a list of paths matching a pathname pattern.
    [...]
    """
    return list(iglob(pathname, recursive=recursive))

What is the point of the *?

Asked By: BiBi

||

Answers:

The * indicates the end of the positional arguments. Every argument after that can only be specified by keyword. This is defined in PEP 3102

>>> def foo1(a, b=None):
...     print(a, b)
...
>>> def foo2(a, *, b=None):
...     print(a, b)
...
>>> foo1(1, 2)
1 2
>>> foo2(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo1() takes 1 positional argument but 2 were given
>>> foo2(1, b=2)
1 2
Answered By: Adam Smith

All arguments after the * must have their name explicitly specified. For example, if you had this function:

def somefunction(a,*,b):
    pass

You could write this:

somefunction(0, b=0)

but not this:

somefunction(0, 0)
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.