32

I was looking at the definition of the glob function and I noticed that the second argument 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 *?

BiBi
  • 6,378
  • 4
  • 38
  • 62

2 Answers2

65

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
user2357112
  • 235,058
  • 25
  • 372
  • 444
Adam Smith
  • 48,602
  • 11
  • 68
  • 105
  • 1
    Interestingly, TensorFlow uses `_sentinel` as a first argument to some of its functions to prevent positional parameters. I'm wondering why they don't simply use `*`. – BiBi Dec 15 '18 at 20:53
  • 3
    @AdamSmith I think you mean keyword only arguments, i.e. PEP 3102. PEP 570 seems to use `/` to define "Positional-Only Parameters" – Sam Mason Dec 15 '18 at 21:05
  • 3
    @BiBi: Python 2 support. Python 2 doesn't have this syntax. – user2357112 Dec 15 '18 at 22:13
  • @SamMason sorry, you're right -- good catch! (and thanks for the edit, user2357112) – Adam Smith Dec 15 '18 at 23:44
4

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)
Pika Supports Ukraine
  • 3,394
  • 9
  • 24
  • 41
  • 1
    You have answered 2 post with the same question: https://stackoverflow.com/questions/53795545/python-init-argument/53795611#53795611 you should mark as a duplicate :-) – eyllanesc Dec 15 '18 at 20:44