Search code examples
pythonpython-3.xpython-3.8pep570

Why use positional-only parameters in Python 3.8+?


A new "positional-only parameters" syntax has been introduced in 3.8.

From Positional-only parameters in the documentation:

There is new syntax (/) to indicate that some function parameters must be specified positionally (i.e., cannot be used as keyword arguments). This is the same notation as shown by help() for functions implemented in C (produced by Larry Hastings’ Argument Clinic tool).

Why ever use this syntax? Why is it better for the code's user?

It seems to me that this makes it harder for users to specify what their arguments actually mean, if they so desire. Why make it harder on the user?


Solution

  • To briefly summarize the stated rationales in PEP 570, the PEP that added positional-only arguments:

    1. Many built-in functions implemented in C already did not accept keyword arguments, even before Python 3.8. Allowing positional-only argument allows python code to be consistent with C code
    2. Some python classes, such as the constructor for the dict type, take arbitrary keyword arguments. If you were to try to define a class with such behavior in python, you would have to write def __init__(self, **kwds), ... except then you can't have a keyword argument named self!. Positional-only arguments can avoid this flaw.
    3. Some functions don't have any natural name to assign their argument to. Take the int constructor. int(x="3") is no more readable than int("3"). Positional-only arguments allow names that have no inherent meaning to be considered implementation details rather than part of the public API of the module.

    There are a few more details in the PEP, but those three points summarize the general reason for the existence of the feature.