Positional Only Arguments In Python
1 min readFeb 23, 2022
- In 2018 the PEP 570 introduced support for positional-only args
- Available in 3.8 and later
- Positional-only can never be passed with a keyword
- Any attempt to pass a keyword arg will result in a
TypeError
def number_length(x,/):
return len(str(x))
>>> number_length("abcdef")
6
>>> number_length(x="abcdef")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: number_length() got some positional-only arguments passed as keyword arguments: 'x'
number_length() got some positional-only arguments passed as keyword arguments: 'x'
- Details are wonderfully covered in Strict Python function parameters
- There are two major reasons for this language feature
- Parity with modules implemented in other languages © that have historically been implementing this already
- Prevent certain argument names from becoming part of the API; this prevents dependencies on the names which is wseful when the names have no semantic meaning