How to Specify Positional-Only Parameters in Python
If you're familiar with Python's keyword-only arguments, then you've probably wondered why the same constraint doesn't exist for positional arguments. This changes with Python 3.8's introduction of positional-only parameters.
Keyword-only arguments
In case you're not familiar with keyword-only arguments, I'll give a quick overview. Any keyword argument defined after an *
will be required as a named argument. See the following examples:
def my_function(arg1, arg2, *, kwarg1=False, kwarg2=True):
pass
In the above function, both kwarg1
and kwarg2
will be required as keyword arguments. This means the user cannot call the function with all positional arguments. See what happens:
>>> my_function(1, 2, 3, 4)
---------------------------------------------------------------------------
TypeError: my_function() takes 2 positional arguments but 4 were given
Instead, we must use:
>>> my_function(1, 2, kwargs1=3, kwarg2=4)
Position-only parameters
We can also require that arguments be specified as positional-only, meaning they cannot be specified as keyword arguments.
The main reason for using either keyword-only or positional-only arguments is to improve readability. However, one advantage to using positional-only arguments is that it improves performance. The parsing and handling of positional arguments is faster than keyword arguments.