Search code examples
pythonfunctionpositional-argument

positional arguments


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


Solution

  • 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.