57

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

BiBi
  • 7,418
  • 5
  • 43
  • 69
  • 3
    Correction: *parameter*, not *argument* – wjandrea Feb 13 '20 at 14:24
  • @wjandrea I'm not a native english speaker, would you please explain the difference or link a source which explains it? In swedish "parameter" means argument, also in italian we don't have a word to say argument because "argomento" is a false friend, so I always used "parametro" as a translation for "argument". – FLAK-ZOSO Mar 21 '23 at 15:21
  • 1
    @FLAK-ZOSO [What is the difference between arguments and parameters? - Python FAQ](https://docs.python.org/3/faq/programming.html#what-is-the-difference-between-arguments-and-parameters) – wjandrea Mar 21 '23 at 16:03
  • @wjandrea thank you a lot! In italian we used to call them "parametri formali" (for "parameters") and "parametri attuali" (for "arguments"), now I got it. – FLAK-ZOSO Mar 21 '23 at 21:39
  • 1
    @wjandrea finally edited the question, 3y later :p. – BiBi Mar 22 '23 at 09:24

2 Answers2

110

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
  • 260,549
  • 28
  • 431
  • 505
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • 2
    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
  • 5
    @BiBi: Python 2 support. Python 2 doesn't have this syntax. – user2357112 Dec 15 '18 at 22:13
  • 1
    @SamMason sorry, you're right -- good catch! (and thanks for the edit, user2357112) – Adam Smith Dec 15 '18 at 23:44
9

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,612
  • 10
  • 26
  • 42
  • 2
    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