top | item 43294316

(no title)

hermitdev | 1 year ago

> Which is redundant for most functions as they only have positional parameters.

Huh? This is not true.

    def foo(a, b, c): ...
This can be invoked as either `foo(1, 2, 3)` or `foo(c=3, b=2, a=1)`:

    >>> def foo(a, b, c):
    ...     print(f"{a=}")
    ...     print(f"{b=}")
    ...     print(f"{c=}")
    ...
    >>> foo(1, 2, 3)
    a=1
    b=2
    c=3
    >>> foo(c=3, b=2, a=1)
    a=1
    b=2
    c=3
    >>>

discuss

order

emmelaich|1 year ago

    Help on built-in function sin in module math:

    sin(x, /)
        Return the sine of x (measured in radians).

   
   >>> math.sin(x=2)
    ~~~~~~~~^^^^^
      TypeError: math.sin() takes no keyword arguments
/ is used everwhere and it's usually just noise. Unexplained noise.

mananaysiempre|1 year ago

It is often used for builtins, because emulating the default Python behaviour of accepting arguments both by position and by name is a pain with the Python/C API. (There are other use cases for positional-only arguments, such as accepting an arbitrary function and an arbitrary set of arguments to call it with at the same time—for example, to invoke it in a new coroutine—but they are pretty rare.) This pecularity of most builtin functions has been there since before Python 3 was a thing, it’s just been undocumented and difficult to emulate in Python before this syntax was introduced.

As for unexplained noise—well, all other parts of the function declaration syntax aren’t explained either. You’re expected to know the function declaration syntax in order to read help on individual function declarations; that’s what the syntax reference is for.