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 *
?
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
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)
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 *
?
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
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)