3

I am trying to understand how the parameters to this function are interpreted:

def f(a, *, b):
   return a, b

It appears this function forces the caller to call f() with exactly 2 params and the second param should always be a named b= param. How do I decipher this from the function signature? Why does it not allow me to specify a middle argument for the *?

Mohd
  • 5,075
  • 7
  • 17
  • 29
user2399453
  • 2,378
  • 2
  • 22
  • 49

2 Answers2

4

How do I decipher this from the function signature?

  1. Arguments with no default value must be passed.
  2. Arguments after a * must be passed by keyword if they are passed at all.
  3. Extra arguments cannot be passed to "fill up" the * unless an argument name accompanies the *.

Since b has no default value it must be passed. Since it is after the * it must be passed by keyword. Since the * is "bare" (i.e., it is just the * placeholder and not a vararg like *args), no other positional arguments can be passed as "middle" arguments.

See PEP 3102 for a description of the keyword-only-argument syntax.

BrenBarn
  • 210,788
  • 30
  • 364
  • 352
3

The * alone is a Python3-only way to express that the following parameters are named arguments and can only be passed to the function as such.

From the documentation:

Parameters after “*” or “*identifier” are keyword-only parameters and may only be passed used keyword arguments.

ramnes
  • 1,221
  • 1
  • 6
  • 12